Skip to content

04 Lambda Functions

DodaTech 1 min read

title: AWS Lambda Functions for Serverless APIs weight: 14 date: 2026-06-28 lastmod: 2026-06-28 description: Learn AWS Lambda function structure including handler patterns, event object structure, context object, response formatting for API Gateway, and error handling best practices. tags: [api-development, serverless]


AWS Lambda functions follow a handler pattern receiving event and context parameters, with the event structure varying by trigger source (API Gateway, S3, DynamoDB Streams) and the response format matching the expected integration format.

```python
import json
import logging

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

def lambda_handler(event, context):
    logger.info(f"Event: {json.dumps(event)}")
    logger.info(f"Remaining time: {context.get_remaining_time_in_millis()}ms")

    try:
        # Extract path parameters
        path_params = event.get("pathParameters", {}) or {}
        user_id = path_params.get("user_id")

        # Extract query parameters
        query_params = event.get("queryStringParameters", {}) or {}
        page = query_params.get("page", "1")

        # Extract body
        body = {}
        if event.get("body"):
            body = json.loads(event["body"])

        # Business logic
        result = {"user_id": user_id, "page": page, "data": body}

        return {
            "statusCode": 200,
            "headers": {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*"
            },
            "body": json.dumps(result)
        }
    except Exception as e:
        logger.error(f"Error: {str(e)}")
        return {
            "statusCode": 500,
            "body": json.dumps({"error": "Internal server error"})
        }

What's Next

Now learn about Lambda layers in Building Serverless APIs.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro