Mangum Documentation

repository·main·Indexed 24 days ago

https://github.com/kludex/mangum

Mangum is an adapter that allows ASGI applications, such as FastAPI, Starlette, Quart, and Django, to run on AWS Lambda by translating Lambda events into the ASGI format. It supports event sources including API Gateway (HTTP and REST), Application Load Balancer (ALB), Lambda Function URLs, and CloudFront Lambda@Edge.

Tokens
5.9K
Snippets
19
Records
42
Agent score
79%

What's inside mangum

  1. What is Mangum and when to use it

    main

    Mangum is an adapter designed to run ASGI applications within AWS Lambda. It acts as the bridge between AWS Lambda events and your ASGI application, allowing you to deploy web frameworks to serverless environments.

    Supported AWS Event Sources

    • API Gateway (both HTTP and REST APIs)
    • Application Load Balancer (ALB)
    • Lambda Function URLs
    • CloudFront Lambda@Edge

    Supported Frameworks

    It is compatible with any ASGI-compliant framework, including:

    • FastAPI
    • Starlette
    • Quart
    • Django
  2. What is the Mangum adapter?

    main
    The Mangum adapter is a configurable wrapper that allows any ASGI application (such as FastAPI, Starlette, or Quart) to run in an AWS Lambda deployment. It acts as the bridge between the AWS Lambda event/context and the ASGI interface.
  3. How Mangum works with ASGI frameworks

    main

    Mangum is an adapter designed to work with any ASGI (Asynchronous Server Gateway Interface) application. Because it relies on the ASGI specification, it does not have framework-specific rules or dependencies. As long as your application exposes an ASGI-compatible interface, Mangum can wrap it.

    An ASGI-compatible application must implement the following protocol:

    class Application(Protocol):
        async def __call__(self, scope: Scope, receive: ASGIReceive, send: ASGISend) -> None:
            ...

    Note on AWS Lambda Limitations: While Mangum provides interoperability, some framework behaviors may conflict with AWS Lambda limitations (such as a read-only file system). These issues should generally be addressed within the framework configuration rather than Mangum.

    class Application(Protocol):
        async def __call__(self, scope: Scope, receive: ASGIReceive, send: ASGISend) -> None:
            ...
  4. How the HTTPCycle state machine works

    main

    The HTTPCycle is a state machine used by the Mangum adapter to manage the communication of message events between the ASGI application and AWS. It handles the entire lifecycle of an ASGI request and response cycle.

    Key components:

    • HTTPCycle: Manages the run, receive, and send operations to bridge the application and the AWS event.
    • HTTPCycleState: Represents the internal state of the request/response cycle.
  5. Configure compression behavior

    main
    Mangum handles compressed responses based on the Content-Encoding header. If the Content-Encoding header is set to gzip or br (Brotli), Mangum will return a binary response (base64 encoded with isBase64Encoded=True) regardless of the Content-Type MIME type.
  6. Configure Mangum lifespan settings

    main

    When initializing Mangum(app, ...), you can specify the lifespan parameter.

    In the provided examples, lifespan="off" is used. This is common in Lambda environments where the ASGI lifespan protocol (startup/shutdown events) might not behave as expected due to the ephemeral nature of Lambda execution environments.

  7. Create an AWS Lambda handler with Mangum

    main

    To use Mangum as your Lambda entry point, wrap your ASGI application instance with Mangum. The resulting object implements a __call__ method, allowing it to be used directly as the Lambda handler function.

    from mangum import Mangum
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    def read_root():
        return {"Hello": "World"}
    
    # This 'handler' is what you point your AWS Lambda configuration to
    handler = Mangum(app)
    from mangum import Mangum
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    def read_root():
        return {"Hello": "World"}
    
    @app.get("/items/{item_id}")
    def read_item(item_id: int, q: str = None):
        return {"item_id": item_id, "q": q}
    
    handler = Mangum(app)
  8. Deploy Python web apps as AWS Lambda functions

    main
    For a comprehensive step-by-step guide on packaging and deploying a Python web application to AWS Lambda, including the specific steps to use Mangum to wrap an ASGI application, refer to the tutorial by Simon Willison.
  9. Set up the Mangum repository for development

    main

    To contribute to Mangum, fork the repository on GitHub and clone your fork locally. You should also add the original repository as an upstream remote to keep your local environment in sync with the main project.

    Follow these steps:

    1. Clone your fork.
    2. Add the upstream remote.
    3. Fetch the latest changes from upstream.
    4. Pull upstream/main into your local branch to stay updated.
    # Clone your fork
    git clone git@github.com:<YOUR-USERNAME>/mangum.git
    
    # Add upstream remote
    cd mangum
    git remote add upstream git://github.com/jordaneremieff/mangum.git
    git fetch upstream
    
    # Sync with main
    git pull upstream main
  10. Run tests and check code coverage

    main

    Use the ./scripts/test script to run the full test suite using PyTest. This script also runs Coverage to generate a report.

    Coverage Requirements: While not a strict requirement for all contributions, the coverage script is configured to fail if coverage is below 100%. It is recommended to include at least one test per PR. You can exclude specific cases from coverage using # pragma: no cover comments.

    ./scripts/test