DEV Community

Anna lilith
Anna lilith

Posted on

Deploy Python Functions to AWS Lambda in 5 Minutes

Deploy Python Functions to AWS Lambda in 5 Minutes

Tags: python, aws, serverless, deployment

Why Lambda?

AWS Lambda lets you run code without servers. Pay only for compute time. Perfect for APIs, data processing, and automation scripts.

Quick Deployment with SAM

# Install AWS SAM CLI
pip install aws-sam-cli

# Initialize a new SAM project
sam init --runtime python3.12 --name my-function

# Build and deploy
sam build
sam deploy --guided
Enter fullscreen mode Exit fullscreen mode

Minimal Lambda Function

import json
import os
from datetime import datetime

def handler(event, context):
    """Process API Gateway events."""

    # Parse request
    path = event.get('path', '/')
    method = event.get('httpMethod', 'GET')
    body = json.loads(event.get('body', '{}')) if event.get('body') else {}

    # Route handling
    if path == '/health':
        response = {
            'status': 'healthy',
            'timestamp': datetime.utcnow().isoformat(),
            'region': os.environ.get('AWS_REGION', 'unknown'),
        }
    elif path == '/process' and method == 'POST':
        # Example: process data
        result = process_data(body)
        response = {'result': result}
    else:
        response = {'error': 'Not found'}

    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
        },
        'body': json.dumps(response)
    }


def process_data(data):
    """Example data processing."""
    return {
        'processed': True,
        'items': len(data.get('items', [])),
        'timestamp': datetime.utcnow().isoformat()
    }
Enter fullscreen mode Exit fullscreen mode

Environment Variables

# template.yaml
Globals:
  Function:
    Timeout: 30
    Runtime: python3.12
    MemorySize: 256
    Environment:
      Variables:
        TABLE_NAME: !Ref DataTable
        AWS_REGION: !Ref AWS::Region
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Cold starts: Keep functions warm with CloudWatch Events
  2. Memory: More memory = faster execution = lower cost
  3. Layers: Share dependencies across functions
  4. Errors: Always return proper error responses
  5. Logging: Use CloudWatch structured logging

Cost Optimization

Lambda charges per request and per GB-second:

  • First 1M requests/month: FREE
  • 400,000 GB-seconds/month: FREE
  • Typical API call: ~$0.0000002

Related Products

Need serverless templates and deployment scripts? We have production-ready Lambda packages at our store.

Browse the collection →

Top comments (0)