Define Lambda function handler in Python - AWS Lambda

Define Lambda function handler in Python

The Lambda functionhandleris 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:

defhandler_name(event, context): ... returnsome_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 theFunctionspage of the Lambda console and choose your function.

  2. Choose theCodetab.

  3. Scroll down to theRuntime settingspane and chooseEdit.

  4. InHandler,enter the new name for your function handler.

  5. ChooseSave.

How it works

When Lambda invokes your function handler, theLambda runtimepasses two arguments to the function handler:

  • The first argument is theevent object.An event is a JSON-formatted document that contains data for a Lambda function to process. TheLambda runtimeconverts the event to an object and passes it to your function code. It is usually of the Pythondicttype. It can also belist,str,int,float,or theNoneTypetype.

    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, seeInvoking Lambda with events from other AWS services.

  • The second argument is thecontext 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 typeand theservicethat invoked the function. For example:

  • If you use theRequestResponseinvocation 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 theRequestResponseinvocation 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 byjson.dumps,the runtime returns an error.

  • If the handler returnsNone,as Python functions without areturnstatement implicitly do, the runtime returnsnull.

  • If you use theEventinvocation type (anasynchronous 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 fileto run the functions in this section. These functions use standard Python libraries which are included with the Lambda runtime you selected. For more information, seeDeployment package.

Returning a message

The following example shows a function calledlambda_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 calledlambda_handler.The function uses event data passed by Lambda at runtime. It parses theenvironment variableinAWS_REGIONreturned 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, seeUse Lambda environment variables to configure values in code.

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

Returning a calculation

The following example shows a function calledlambda_handler.The function accepts user input and returns a calculation to the user. For more information about this example, see theaws-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 onexecution environmentstartup.

  • 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/tmpdirectory. 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, seeReusing Connections with Keep-Alive in Node.js.

  • Useenvironment variablesto 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 codein your Lambda function, wherein the function automatically calls itself until some arbitrary criteria is met. This could lead to unintended volume of function invocations and escalated costs. If you do accidentally do so, set the function reserved concurrency to0immediately to throttle all invocations to the function, while you update the code.

  • Do not use non-documented, non-public APIsin 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 referencefor 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?.