Skip to content

Adapter

The heart of Mangum is the adapter class. It is a configurable wrapper that allows any ASGI application (or framework) to run in an AWS Lambda deployment. The adapter accepts a number of keyword arguments to configure settings related to logging, HTTP responses, ASGI lifespan, and API Gateway configuration.

handler = Mangum(
    app,
    lifespan="auto",
    log_level="info",
    api_gateway_base_path=None,
    text_mime_types=None
)

Configuring an adapter instance

class mangum.adapter.Mangum(app, lifespan='auto', log_level='info', api_gateway_base_path=None, text_mime_types=None)

Creates an adapter instance.

  • app - An asynchronous callable that conforms to version 3.0 of the ASGI specification. This will usually be an ASGI framework application instance.
  • lifespan - A string to configure lifespan support. Choices are auto, on, and off. Default is auto.
  • log_level - A string to configure the log level. Choices are: info, critical, error, warning, and debug. Default is info.
  • api_gateway_base_path - Base path to strip from URL when using a custom domain name.
  • text_mime_types - A list of MIME types to include with the defaults that should not return a binary response in API Gateway.

Creating an AWS Lambda handler

The adapter can be used to wrap any application without referencing the underlying methods. It defines a __call__ method that allows the class instance to be used as an AWS Lambda event handler function.

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)

However, this is just one convention, you may also intercept events and construct the adapter instance separately. This may be useful if you need to implement custom event handling. The handler in the example above could be replaced with a function.

def handler(event, context):
    if event.get("some-key"):
        # Do something or return, etc.
        return

    asgi_handler = Mangum(app)
    response = asgi_handler(event, context) # Call the instance with the event arguments

    return response

Retrieving the AWS event and context

The AWS Lambda handler event and context arguments are made available to an ASGI application in the ASGI connection scope.

scope['aws.event']
scope['aws.context']

For example, if you're using FastAPI it can be retrieved from the scope attribute of the request object.

from fastapi import FastAPI
from mangum import Mangum
from starlette.requests import Request

app = FastAPI()


@app.get("/")
def hello(request: Request):
    return {"aws_event": request.scope["aws.event"]}

handler = Mangum(app)