On this page
article
AWS Lambda with Python
Build and deploy Python functions on AWS Lambda — handler functions, event sources, layers, and API Gateway integration.
AWS Lambda runs your Python code in response to events. You upload a function, configure triggers, and AWS handles everything else — scaling, patching, monitoring.
Your First Lambda Function
# lambda_function.py
import json
def lambda_handler(event, context):
name = event.get('name', 'World')
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message': f'Hello, {name}!'}),
}
Deploy with AWS CLI
# Package the function
zip function.zip lambda_function.py
# Create the function
aws lambda create-function \
--function-name hello-python \
--runtime python3.12 \
--handler lambda_function.lambda_handler \
--role arn:aws:iam::ACCOUNT:role/lambda-execution-role \
--zip-file fileb://function.zip
# Invoke it
aws lambda invoke \
--function-name hello-python \
--payload '{"name": "Alice"}' \
response.json
cat response.json
API Gateway Integration
Expose your Lambda as a REST API:
def lambda_handler(event, context):
http_method = event['httpMethod']
path = event['path']
if http_method == 'GET' and path == '/items':
return {
'statusCode': 200,
'body': json.dumps([{'id': 1, 'name': 'Item 1'}]),
}
if http_method == 'POST' and path == '/items':
body = json.loads(event['body'])
return {
'statusCode': 201,
'body': json.dumps({'id': 2, 'name': body['name']}),
}
return {'statusCode': 404, 'body': json.dumps({'error': 'Not found'})}
Environment Variables
import os
DATABASE_URL = os.environ['DATABASE_URL']
API_KEY = os.environ['API_KEY']
def lambda_handler(event, context):
# Use environment variables for configuration
...
Set via CLI:
aws lambda update-function-configuration \
--function-name hello-python \
--environment "Variables={DATABASE_URL=postgres://...,API_KEY=secret}"
Lambda Layers
Share dependencies across functions:
# Build a layer with dependencies
mkdir -p python/lib/python3.12/site-packages
pip install requests boto3 -t python/lib/python3.12/site-packages/
zip -r layer.zip python
aws lambda publish-layer-version \
--layer-name python-deps \
--zip-file fileb://layer.zip \
--compatible-runtimes python3.12
Event Sources
| Trigger | Use Case |
|---|---|
| API Gateway | REST/HTTP APIs |
| S3 | File upload processing |
| SQS | Message queue processing |
| DynamoDB Streams | Database change reactions |
| EventBridge | Scheduled tasks (cron) |
| SNS | Notification processing |
S3 Trigger Example
import boto3
import json
s3 = boto3.client('s3')
def lambda_handler(event, context):
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
print(f"Processing {key} from {bucket}")
response = s3.get_object(Bucket=bucket, Key=key)
content = response['Body'].read().decode('utf-8')
# Process the file...
Best Practices
- Keep functions small and focused — one responsibility per function
- Use environment variables for configuration, not hardcoded values
- Set appropriate timeouts — default is 3 seconds, max is 15 minutes
- Use Lambda Layers for shared dependencies to reduce deployment package size
- Enable X-Ray tracing for debugging distributed applications
- Handle cold starts — keep packages lean, use provisioned concurrency for latency-sensitive apps
AWS Lambda is the most mature serverless platform with the largest ecosystem of integrations.