Mock Lambda handler event context dict in Python

Simulates an AWS Lambda invocation by passing a mock event dict and context object to a handler, then prints the response.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 14 views 0 copies

Python code

44 lines
Python 3.9+
import json


def lambda_handler(event, context):
    """
    A mock AWS Lambda handler that processes an event dict and context object.
    Demonstrates the typical Lambda function signature and basic event/context usage.
    """
    print("Received event:", json.dumps(event, indent=2))
    print("Function name:", context.function_name)
    print("AWS Request ID:", context.aws_request_id)
    print("Memory limit (MB):", context.memory_limit_in_mb)
    
    # Simple response echoing the event data
    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "Hello from mock Lambda!",
            "received_key": event.get("key", "default"),
            "function_name": context.function_name
        }),
        "headers": {
            "Content-Type": "application/json"
        }
    }


class MockContext:
    """Simple mock of the Lambda context object."""
    function_name = "my-mock-function"
    aws_request_id = "mock-request-id-123456"
    memory_limit_in_mb = 128


if __name__ == "__main__":
    # Simulate an AWS Lambda invocation
    mock_event = {
        "key": "value123",
        "extra": "data"
    }
    mock_context = MockContext()
    
    result = lambda_handler(mock_event, mock_context)
    print("Response:", result)

Output

stdout
Received event: {
  "key": "value123",
  "extra": "data"
}
Function name: my-mock-function
AWS Request ID: mock-request-id-123456
Memory limit (MB): 128
Response: {'statusCode': 200, 'body': '{"message": "Hello from mock Lambda!", "received_key": "value123", "function_name": "my-mock-function"}', 'headers': {'Content-Type': 'application/json'}}

How it works

The handler follows the standard AWS Lambda signature: (event, context). The event is a plain dictionary that AWS passes as a JSON object; here we provide a mock dict. The context is an object with attributes like function_name, aws_request_id, and memory_limit_in_mb; our MockContext replicates these. json.dumps(event, indent=2) makes the event readable. Calling event.get("key", "default") safely reads a key that may be missing. The mock context lets you test handler logic locally without AWS.

Common mistakes

  • Forgetting that `context` is an object, not a dict — access attributes, not keys.
  • Not mocking context attributes that your handler actually uses, causing AttributeError.
  • Returning a plain string instead of the statusCode/body dict that API Gateway expects.

Variations

  1. Use `aws_lambda_powertools` or a pytest fixture to mock the event and context.
  2. Read the event from a JSON file to simulate larger payloads.

Real-world use cases

  • Unit-testing Lambda handlers locally before deploying to AWS.
  • Developing and debugging serverless functions in a local IDE without cloud access.
  • Automating integration tests that call the handler with realistic event fixtures.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.