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
app.py under the
hello_world folder. Note that your function may have additional commented out code, those lines have been removed from the following example for clarity:
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
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.
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: https://docs.aws.amazon.com/lambda/latest/dg/lambda-services.html
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.
API Gateway expects the handler to return a response object that contains statusCode and body, but it can also contain optional headers.