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",
api_gateway_base_path=None,
custom_handlers=None,
text_mime_types=None,
)
All arguments are optional.
Configuring an adapter instance
mangum.adapter.Mangum
(app, lifespan='auto', api_gateway_base_path='/', custom_handlers=None, text_mime_types=None, exclude_headers=None)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)