Mangum
Mangum is an adapter designed to run ASGI (Asynchronous Server Gateway Interface) applications, such as FastAPI, Starlette, Quart, and Django, within AWS Lambda environments. It handles various AWS event types including Function URLs, API Gateway (HTTP and REST APIs), Application Load Balancer, and CloudFront Lambda@Edge. The library is actively maintained, with frequent releases, and is currently at version 0.21.0.
Warnings
- breaking Mangum dropped official support for Python 3.7 and Python 3.8 in version 0.20.0. Applications targeting these Python versions should remain on an older Mangum release (e.g., 0.19.0 or earlier) or upgrade their Python runtime to 3.9 or newer.
- gotcha When deploying FastAPI applications behind AWS API Gateway with custom base paths or stages, incorrect routing ('not found' errors) can occur. It's often necessary to configure `api_gateway_base_path` in the Mangum handler and/or `root_path` in your FastAPI app to match the API Gateway setup.
- gotcha The `lifespan` parameter (defaulting to `"off"` in many examples) controls the ASGI lifespan events (startup/shutdown). Setting it to `"on"` or `"auto"` is crucial for applications that require startup tasks (e.g., database connections) or shutdown cleanup. Using `"off"` will prevent these events from running.
- deprecated Version 0.21.0 has introduced a `DeprecationWarning` related to `asyncio.get_event_loop` during Mangum initialization, indicating a potential shift in how event loops are managed or accessed. While currently a warning, it may foreshadow future breaking changes.
- gotcha Handling binary media types (e.g., images, PDFs) or certain text-based content types (e.g., `application/json` with specific charsets) requires careful configuration to prevent data corruption. Headers like `Content-Type` might need explicit handling or inclusion in `text_mime_types` for proper encoding/decoding.
Install
-
pip install mangum
Imports
- Mangum
from mangum import Mangum
Quickstart
from fastapi import FastAPI
from mangum import Mangum
app = FastAPI()
@app.get("/hello")
async def read_root():
return {"message": "Hello from FastAPI on Lambda!"}
handler = Mangum(app)
# To test locally, you would typically run with uvicorn:
# uvicorn main:app --reload --port 8000
# For Lambda, `handler` is the entry point defined in your function configuration.