Building an AWS Lambda Function to Trigger an External HTTP Endpoint

Building an AWS Lambda Function to Trigger an External HTTP Endpoint

AWS Lambda is a serverless compute service that lets you run your code without provisioning or managing servers. In this tutorial, we'll walk through the process of creating an AWS Lambda function in Python to trigger an external HTTP endpoint.

Prerequisites

  1. AWS Account: Make sure you have an AWS account set up.

  2. AWS CLI: Install the AWS Command Line Interface (CLI) on your local machine.

  3. Python and pip: Ensure that Python and pip are installed on your local machine.

Step 1: Set Up Your AWS Lambda Function

Create a New Lambda Function

  1. Open the AWS Lambda Console.

  2. Click on "Create function."

  3. Choose "Author from scratch" and fill in the necessary details.

  4. Select the latest Python runtime.

  5. Click on "Create function."

Configure Environment Variables

  1. In your Lambda function settings, navigate to the "Environment variables" section.

  2. Add a variable named ENDPOINT with the external HTTP endpoint URL.

Step 2: Write the Lambda Function Code

Create a new Python file, e.g., lambda_function.py, and copy the following code:

import json
import logging
import os
import requests

logger = logging.getLogger("lambda-function")
logger.setLevel(logging.INFO)

endpoint = os.environ.get("ENDPOINT")

def lambda_handler(event, context):
    # Extract information from the event
    job_id = event.get("job_id")
    status = event.get("status")
    error_description = event.get("error_description")
    output_file_path = event.get("output_file_path")
    context_data = event.get("context")

    body = {
        "job_id": job_id,
        "status": status,
        "error_description": error_description,
        "output_file_path": output_file_path,
        "context_data": context_data,
        "context": {}
    }

    try:
        headers = {'Content-Type': 'application/json;charset=utf-8'}
        response = requests.post(endpoint, json=body, headers=headers)

        if response.status_code == 200:
            logger.info(
                f"Successfully called {endpoint} for {job_id}. Response: {response.text}"
            )
        else:
            error_message = f"{endpoint} endpoint unreachable. Response: {response.text}"
            logger.error(error_message)
            response.raise_for_status()

    except requests.exceptions.RequestException as re:
        logger.error(f'Request error: {re}')
        raise

    return {
        "statusCode": 200,
        "body": json.dumps("Job status notifier execution completed from Lambda!"),
    }

This code defines an AWS Lambda function that extracts information from the incoming event and sends a POST request to the specified external HTTP endpoint.

Step 3: Deploy and Test Your Lambda Function

  1. Save your Python file and zip it.

  2. Upload the ZIP file to your Lambda function.

  3. Configure a test event with sample data and run a test.

  4. Check the Lambda function logs for any errors or successful execution.

Conclusion

In this tutorial, we've walked through the process of creating an AWS Lambda function in Python to trigger an external HTTP endpoint. Feel free to adapt this example to suit your specific use case and explore additional AWS Lambda features for building powerful serverless applications.

Happy coding!