If you consider yourself an expert using Lambda functions, you can probably skip this page.

Let’s take a look at the code of the Hello World Lambda function. Open the file under the hello_world folder.

import json

# import requests

def lambda_handler(event, context):
    """Sample pure Lambda function

    event: dict, required
        API Gateway Lambda Proxy Input Format

        Event doc:

    context: object, required
        Lambda Context runtime methods and attributes

        Context doc:

    API Gateway Lambda Proxy Output Format: dict

        Return doc:

    # try:
    #     ip = requests.get("")
    # except requests.RequestException as e:
    #     # Send some context about this error to Lambda Logs
    #     print(e)

    #     raise e

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
            # "location": ip.text.replace("\n", "")

Lambda hanlder

The handler is the method in your Lambda function that processes events. When you invoke a function, the runtime runs the handler method. When the handler exits or returns a response, it becomes available to handle another event. In this case, the lambda handler is the lambda_handler function, as specified in the SAM template.yaml.

Because the Lambda handler is executed on every invocation, a best practice is to place code that can be reused across invocations outside of the handler scope. A common example is to initialize database connections outside of the handler.

Event object

The first argument passed to the handler function is the event object, which contains information from the invoker. In this case, the invoker is API Gateway, which passes the HTTP request information as a JSON-formatted string, and the Lambda runtime converts it to an object. You can find examples of event payloads here:

Context object

The second argument is the context object, which contains information about the invocation, function, and execution environment. You can get information like the CloudWatch log stream name or the remaining execution time for the function.

Hanlder response

API Gateway expects the handler to return a response object that contains statusCode and body, but it can also contain optional headers.