apig-wsgi

2.20.0 · active · verified Fri Apr 17

apig-wsgi is a Python library that wraps a standard WSGI application in an AWS Lambda handler function, allowing it to be run on AWS API Gateway (REST API or HTTP API) or an Application Load Balancer (ALB). It's currently on version 2.20.0 and sees active maintenance with several releases per year.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple WSGI application and wrap it with `apig-wsgi` for use as an AWS Lambda handler. It includes a basic `lambda_handler` function and a local `if __name__ == '__main__':` block to simulate an API Gateway V1 event and test the integration without deploying to AWS.

import json
from apig_wsgi import APIGatewayWSGI, APIGatewayEventType

# A simple WSGI application function
def my_wsgi_app(environ, start_response):
    status = '200 OK'
    headers = [('Content-type', 'application/json')]
    start_response(status, headers)
    response_body = {
        "message": "Hello from WSGI on Lambda!",
        "path": environ.get('PATH_INFO', '/'),
        "method": environ.get('REQUEST_METHOD', 'GET'),
        "query_string": environ.get('QUERY_STRING', '')
    }
    return [json.dumps(response_body).encode('utf-8')]

# Instantiate the APIGatewayWSGI handler
# Use APIGatewayEventType.API_GATEWAY_V1 for REST API (default if omitted)
# Use APIGatewayEventType.API_GATEWAY_V2 for HTTP API
# Use APIGatewayEventType.ALB for Application Load Balancer
apig_wsgi_handler = APIGatewayWSGI(my_wsgi_app, gateway_type=APIGatewayEventType.API_GATEWAY_V1)

# This is the standard AWS Lambda handler entry point
def lambda_handler(event, context):
    print(f"Received Lambda event: {json.dumps(event)}")
    response = apig_wsgi_handler(event, context)
    print(f"Returning Lambda response: {json.dumps(response)}")
    return response

# Example of how you would test this locally or simulate an event
if __name__ == "__main__":
    # Simulate an API Gateway V1 (REST API) GET event
    mock_event_v1 = {
        "resource": "/hello", "path": "/hello", "httpMethod": "GET",
        "headers": {"Accept": "*/*", "User-Agent": "test-client"},
        "queryStringParameters": {"name": "Registry"},
        "requestContext": {"resourceId": "xxx", "apiId": "yyy", "resourcePath": "/hello", "httpMethod": "GET",
            "requestId": "uuid", "identity": {"sourceIp": "127.0.0.1"}, "path": "/hello"},
        "body": None, "isBase64Encoded": False
    }
    mock_context = {}

    print("--- Testing API Gateway V1 event ---")
    lambda_response = lambda_handler(mock_event_v1, mock_context)
    print("\nSimulated API Gateway V1 Lambda Response:")
    print(json.dumps(lambda_response, indent=2))

view raw JSON →