← All notes

FastAPI middleware - add_middleware, CORSMiddleware and @app.middleware

Answer: FastAPI applications can have middleware. Middleware is a function that works with every request. It also runs on every response before returning it. Add it with add_middleware, or with @app.middleware("http").

Examples

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://example.com"],
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.middleware("http")
async def add_request_id(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-App"] = "demo"
    return response

Rules

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: FastAPI docs, Middleware; fastapi/fastapi (GitHub), tutorial/middleware.md. MIT (https://raw.githubusercontent.com/fastapi/fastapi/master/LICENSE). Copyright FastAPI contributors. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: FastAPI docs, Middleware; fastapi/fastapi (GitHub), tutorial/middleware.md. MIT (https://raw.githubusercontent.com/fastapi/fastapi/master/LICENSE). Copyright FastAPI contributors.

Cite this

Permanent ID: iil:note:1xfh3ww9

iinventedlight. 2026. "FastAPI middleware - add_middleware, CORSMiddleware and @app.middleware." iinventedlight Library, iil:note:1xfh3ww9, version of 2026-11-18. https://iinventedlight.com/library/notes/fastapi-middleware/. License: CC-BY-4.0.

@misc{iil_note_1xfh3ww9,
  author = {{iinventedlight}},
  title = {{FastAPI middleware - add\_middleware, CORSMiddleware and @app.middleware}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/fastapi-middleware/},
  note = {Permanent ID iil:note:1xfh3ww9. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/fastapi-middleware.md.