Add Custom Header in Middleware in FastAPI: Simple Guide
In FastAPI, you can add a custom header in middleware by creating a middleware function that modifies the response headers before returning it. Use
@app.middleware("http") decorator and add headers to the response.headers dictionary.Syntax
To add a custom header in FastAPI middleware, define a function decorated with @app.middleware("http"). This function receives request and call_next. Call call_next(request) to get the response, then add your custom header to response.headers before returning it.
@app.middleware("http"): Registers the middleware.request: Incoming HTTP request.call_next(request): Calls the next middleware or endpoint and returns the response.response.headers: Dictionary to add or modify HTTP headers.
python
from fastapi import FastAPI from starlette.requests import Request app = FastAPI() @app.middleware("http") async def add_custom_header(request: Request, call_next): response = await call_next(request) response.headers["X-Custom-Header"] = "MyValue" return response
Example
This example shows a FastAPI app with middleware that adds a custom header X-Custom-Header with value MyValue to every response. When you visit the root endpoint, the response will include this header.
python
from fastapi import FastAPI from starlette.requests import Request app = FastAPI() @app.middleware("http") async def add_custom_header(request: Request, call_next): response = await call_next(request) response.headers["X-Custom-Header"] = "MyValue" return response @app.get("/") async def root(): return {"message": "Hello, world!"}
Output
HTTP/1.1 200 OK
content-length: 25
content-type: application/json
x-custom-header: MyValue
{"message":"Hello, world!"}
Common Pitfalls
Common mistakes when adding custom headers in FastAPI middleware include:
- Not awaiting
call_next(request), which causes errors or no response. - Modifying headers before calling
call_next, which has no effect because the response is created after. - Returning the original response without adding headers.
Always add headers after getting the response from call_next.
python
from fastapi import FastAPI from starlette.requests import Request from starlette.responses import JSONResponse app = FastAPI() # Wrong: modifying headers before call_next @app.middleware("http") async def wrong_middleware(request: Request, call_next): response = JSONResponse({"message": "Hello"}) response.headers["X-Wrong-Header"] = "NoEffect" response = await call_next(request) return response # Right: modify headers after call_next @app.middleware("http") async def right_middleware(request: Request, call_next): response = await call_next(request) response.headers["X-Right-Header"] = "Works" return response
Quick Reference
- Use
@app.middleware("http")to create middleware. - Always
await call_next(request)to get the response. - Add custom headers by setting
response.headers["Header-Name"] = "value". - Modify headers only after receiving the response.
Key Takeaways
Add custom headers in FastAPI middleware by modifying response.headers after awaiting call_next(request).
Always await call_next(request) to get the response before changing headers.
Do not modify headers before calling call_next, as it won't affect the response.
Use @app.middleware("http") decorator to register middleware functions.
Custom headers help add metadata or control information to all responses easily.