AWS Tutorials

How to Create an AWS Lambda Function in Python

Create an AWS Lambda function in Python: write the handler, test it in the console, read the CloudWatch logs, package dependencies, and deploy it from the CLI.

On this page
  1. What you’ll build
  2. Before you start
  3. Step 1: Create the function in the console
  4. Step 2: Write the handler
  5. Step 3: Test with a test event
  6. Step 4: Read the logs
  7. Step 5: Package a dependency (optional)
  8. Step 6: Deploy from the command line
  9. Limits and costs
  10. Troubleshooting
  11. Clean up
  12. Next steps

What you’ll build

You will create a Python Lambda function that multiplies two numbers and returns the area of a rectangle. You will test it in the console, read its logs in CloudWatch, and then deploy the same code from the command line.

Before you start

  • An AWS account and an IAM user with permission to create Lambda functions and IAM roles.
  • Python 3 on your computer, if you want to package dependencies.
  • The AWS CLI version 2, if you want to follow the command-line steps.

Step 1: Create the function in the console

Open the Lambda console and choose Create function. The button label can change between console versions, so look for the option that creates a function from scratch.

  • Function name: myLambdaFunction.
  • Runtime: a supported Python version, such as 3.13 or 3.14. The console lists the current options.
  • Architecture: x86_64 is a safe default.
  • Execution role: let Lambda create a new role with basic permissions. That role can write logs to CloudWatch.

Choose Create function. Lambda creates a file called lambda_function.py with a sample handler.

Step 2: Write the handler

Replace the code in lambda_function.py with this:

import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_handler(event, context):
    length = event["length"]
    width = event["width"]
    area = length * width

    logger.info("Calculated area: %s", area)
    return json.dumps({"area": area})

Choose Deploy to save the change. A few details matter:

  • The handler is lambda_function.lambda_handler. The file name is lambda_function.py, and the function name is lambda_handler. If you rename either one, update the handler setting to match.
  • event holds the input. For this example, it is a JSON object with length and width.
  • context holds information about the invocation, such as the log group name.

Step 3: Test with a test event

In the console, open the Test section and create a test event. Name it myTestEvent and use this JSON:

{
  "length": 6,
  "width": 7
}

Choose Test. The response should be "{\"area\": 42}". The response is a JSON string, which is why the quotes are escaped.

Step 4: Read the logs

Open the Monitor tab, or go to CloudWatch and open the log group /aws/lambda/myLambdaFunction. Each invocation has a log stream. The logger.info line appears there.

Anything your function prints with print() also goes to the same log group, so you can use either method. A logging library gives you levels and a consistent format, which helps when a function runs often.

Step 5: Package a dependency (optional)

Lambda includes the AWS SDK for Python (boto3) in its Python runtimes. For any other library, package it with your code:

mkdir package
pip install -r requirements.txt -t package/
cp lambda_function.py package/
cd package
zip -r ../function.zip .
cd ..

The lambda_function.py file must sit at the root of the zip file, not inside a folder. A common first mistake is to zip the project folder itself, which nests the code one level down.

If a library includes compiled code, the binaries must match Lambda’s operating system and architecture. Build the package on Linux, or in a container that matches the Lambda runtime. Packages built on macOS or Windows can fail with import errors.

Step 6: Deploy from the command line

Create the function from the zip file. Replace the role ARN with the ARN of an IAM role that Lambda can assume and that has CloudWatch Logs permissions. The console-created role works.

aws lambda create-function \
  --function-name myLambdaFunction \
  --runtime python3.13 \
  --handler lambda_function.lambda_handler \
  --zip-file fileb://function.zip \
  --role arn:aws:iam::123456789012:role/<your-lambda-role>

To update the code later, run:

aws lambda update-function-code \
  --function-name myLambdaFunction \
  --zip-file fileb://function.zip

Invoke the function from the terminal:

aws lambda invoke \
  --function-name myLambdaFunction \
  --cli-binary-format raw-in-base64-out \
  --payload '{"length": 6, "width": 7}' \
  response.json
cat response.json

Limits and costs

  • Timeout: the default is 3 seconds, and the maximum is 15 minutes. Raise the timeout if your function calls a slow service.
  • Memory: from 128 MB to 10,240 MB. CPU scales with memory.
  • Temporary storage: /tmp has 512 MB by default, and you can increase it up to 10,240 MB.
  • Payload: synchronous invocations accept up to 6 MB. Environment variables are limited to 4 KB in total.
  • Package size: a direct upload is limited to 50 MB zipped, and 250 MB unzipped.
  • Price: in us-east-1 on x86, about $0.20 per million requests, plus about $0.0000166667 per GB-second of execution. The free tier includes monthly allowances of both. Check the Lambda pricing page for current amounts.

Troubleshooting

  • Unable to import module 'lambda_function'. The handler setting does not match the file name, or the file is nested inside a folder in the zip. Check the zip root with unzip -l function.zip.
  • No module named .... A dependency was not packaged, or it was built for the wrong operating system or architecture.
  • Task timed out after 3.00 seconds. Increase the timeout in the function’s configuration.
  • The test fails with AccessDenied. The execution role lacks a permission the code needs. Add it to the role.

Clean up

To remove what you created, delete the function, the CloudWatch log group /aws/lambda/myLambdaFunction, and the execution role if you no longer need it. The log group keeps its data until you delete it.

aws lambda delete-function --function-name myLambdaFunction

Next steps

The complete guide to aws tutorials

AWS Fundamentals: The Core Cloud Computing Services
Read the guide

Keep exploring

Guides from other topics

All topics →