Define Lambda function handler in Python - AWS Lambda

Define Lambda function handler in Python

The Lambda function handler is the method in your function code that processes events. When your function is invoked, Lambda runs the handler method. Your function runs until the handler returns a response, exits, or times out.

You can use the following general syntax when creating a function handler in Python:

def handler_name(event, context): ... return some_value

Naming

The Lambda function handler name specified at the time that you create a Lambda function is derived from:

  • The name of the file in which the Lambda handler function is located.

  • The name of the Python handler function.

A function handler can be any name; however, the default name in the Lambda console is lambda_function.lambda_handler. This function handler name reflects the function name (lambda_handler) and the file where the handler code is stored (lambda_function.py).

If you create a function in the console using a different file name or function handler name, you must edit the default handler name.

To change the function handler name (console)
  1. Open the Functions page of the Lambda console and choose your function.

  2. Choose the Code tab.

  3. Scroll down to the Runtime settings pane and choose Edit.

  4. In Handler, enter the new name for your function handler.

  5. Choose Save.

How it works

When Lambda invokes your function handler, the Lambda runtime passes two arguments to the function handler:

  • The first argument is the event object. An event is a JSON-formatted document that contains data for a Lambda function to process. The Lambda runtime converts the event to an object and passes it to your function code. It is usually of the Python dict type. It can also be list, str, int, float, or the NoneType type.

    The event object contains information from the invoking service. When you invoke a function, you determine the structure and contents of the event. When an AWS service invokes your function, the service defines the event structure. For more information about events from AWS services, see Invoking Lambda with events from other AWS services.

  • The second argument is the context object. A context object is passed to your function by Lambda at runtime. This object provides methods and properties that provide information about the invocation, function, and runtime environment.

Returning a value

Optionally, a handler can return a value. What happens to the returned value depends on the invocation type and the service that invoked the function. For example:

  • If you use the RequestResponse invocation type, such as Invoke a Lambda function synchronously, AWS Lambda returns the result of the Python function call to the client invoking the Lambda function (in the HTTP response to the invocation request, serialized into JSON). For example, AWS Lambda console uses the RequestResponse invocation type, so when you invoke the function on the console, the console will display the returned value.

  • If the handler returns objects that can't be serialized by json.dumps, the runtime returns an error.

  • If the handler returns None, as Python functions without a return statement implicitly do, the runtime returns null.

  • If you use the Event invocation type (an asynchronous invocation), the value is discarded.

Note

In Python 3.9 and later releases, Lambda includes the requestId of the invocation in the error response.

Examples

The following section shows examples of Python functions you can use with Lambda. If you use the Lambda console to author your function, you do not need to attach a .zip archive file to run the functions in this section. These functions use standard Python libraries which are included with the Lambda runtime you selected. For more information, see Deployment package.

Returning a message

The following example shows a function called lambda_handler. The function accepts user input of a first and last name, and returns a message that contains data from the event it received as input.

def lambda_handler(event, context): message = 'Hello {} {}!'.format(event['first_name'], event['last_name']) return { 'message' : message }

You can use the following event data to invoke the function:

{ "first_name": "John", "last_name": "Smith" }

The response shows the event data passed as input:

{ "message": "Hello John Smith!" }

Parsing a response

The following example shows a function called lambda_handler. The function uses event data passed by Lambda at runtime. It parses the environment variable in AWS_REGION returned in the JSON response.

import os import json def lambda_handler(event, context): json_region = os.environ['AWS_REGION'] return { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": json.dumps({ "Region ": json_region }) }

You can use any event data to invoke the function:

{ "key1": "value1", "key2": "value2", "key3": "value3" }

Lambda runtimes set several environment variables during initialization. For more information on the environment variables returned in the response at runtime, see Create Lambda environment variables.

The function in this example depends on a successful response (in 200) from the Invoke API. For more information on the Invoke API status, see the Invoke Response Syntax.

Returning a calculation

The following example shows a function called lambda_handler. The function accepts user input and returns a calculation to the user. For more information about this example, see the aws-doc-sdk-examples GitHub repository.

import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): ... result = None action = event.get('action') if action == 'increment': result = event.get('number', 0) + 1 logger.info('Calculated result of %s', result) else: logger.error("%s is not a valid action.", action) response = {'result': result} return response

You can use the following event data to invoke the function:

{ "action": "increment", "number": 3 }

Code best practices for Python Lambda functions

Adhere to the guidelines in the following list to use best coding practices when building your Lambda functions:

  • Separate the Lambda handler from your core logic. This allows you to make a more unit-testable function. For example, in Python, this may look like:

    def lambda_handler(event, context): foo = event['foo'] bar = event['bar'] result = my_lambda_function(foo, bar) def my_lambda_function(foo, bar): // MyLambdaFunction logic here
  • Control the dependencies in your function's deployment package. The AWS Lambda execution environment contains a number of libraries. For the Node.js and Python runtimes, these include the AWS SDKs. To enable the latest set of features and security updates, Lambda will periodically update these libraries. These updates may introduce subtle changes to the behavior of your Lambda function. To have full control of the dependencies your function uses, package all of your dependencies with your deployment package.

  • Minimize the complexity of your dependencies. Prefer simpler frameworks that load quickly on execution environment startup.

  • Minimize your deployment package size to its runtime necessities. This will reduce the amount of time that it takes for your deployment package to be downloaded and unpacked ahead of invocation.

  • Take advantage of execution environment reuse to improve the performance of your function. Initialize SDK clients and database connections outside of the function handler, and cache static assets locally in the /tmp directory. Subsequent invocations processed by the same instance of your function can reuse these resources. This saves cost by reducing function run time.

    To avoid potential data leaks across invocations, don’t use the execution environment to store user data, events, or other information with security implications. If your function relies on a mutable state that can’t be stored in memory within the handler, consider creating a separate function or separate versions of a function for each user.

  • Use a keep-alive directive to maintain persistent connections. Lambda purges idle connections over time. Attempting to reuse an idle connection when invoking a function will result in a connection error. To maintain your persistent connection, use the keep-alive directive associated with your runtime. For an example, see Reusing Connections with Keep-Alive in Node.js.

  • Use environment variables to pass operational parameters to your function. For example, if you are writing to an Amazon S3 bucket, instead of hard-coding the bucket name you are writing to, configure the bucket name as an environment variable.

  • Avoid using recursive invocations in your Lambda function, where the function invokes itself or initiates a process that may invoke the function again. This could lead to unintended volume of function invocations and escalated costs. If you see an unintended volume of invocations, set the function reserved concurrency to 0 immediately to throttle all invocations to the function, while you update the code.

  • Do not use non-documented, non-public APIs in your Lambda function code. For AWS Lambda managed runtimes, Lambda periodically applies security and functional updates to Lambda's internal APIs. These internal API updates may be backwards-incompatible, leading to unintended consequences such as invocation failures if your function has a dependency on these non-public APIs. See the API reference for a list of publicly available APIs.

  • Write idempotent code. Writing idempotent code for your functions ensures that duplicate events are handled the same way. Your code should properly validate events and gracefully handle duplicate events. For more information, see How do I make my Lambda function idempotent?.