tezvyn:

FastAPI: Setting Custom Response Headers

AI-drafted, machine-checkedSource: fastapi.tiangolo.comadvanced

Set custom HTTP headers in FastAPI by adding a `Response` parameter to your endpoint. This lets you add metadata like trace IDs without changing your return data. The footgun is thinking you must return the `Response` object; just return your data as usual.

WHY IT EXISTS HTTP headers are the standard way to pass metadata between a client and server that doesn't belong in the response body. You might need to send a custom correlation ID for debugging, a server-side timing metric, or custom caching rules. This pattern provides a clean way to do so without cluttering your data payload.

THE MENTAL MODEL Think of your FastAPI endpoint as returning a data payload (like a dictionary or Pydantic model). By adding a Response parameter to your function, you get a 'sidecar' object representing the final HTTP response envelope. You can add headers to this sidecar, and FastAPI will intelligently merge them into the response it sends to the client, along with your main data payload.

HOW IT WORKS In your path operation function, declare a parameter and type-hint it as response: Response. FastAPI will inject the Response object for you. Inside the function, you can access its .headers attribute like a dictionary and set your custom header, for example: response.headers["X-Trace-ID"] = "some-uuid". Then, simply return your data as you normally would. FastAPI handles combining the headers and your returned data into a single, complete HTTP response.

WHEN TO USE IT Use this technique to add metadata that is separate from your core data model. Three common places this shows up: first, sending a unique request ID for logging and tracing across services; second, providing custom caching instructions with Cache-Control headers; third, indicating API versioning with a custom header like X-API-Version.

WHEN NOT TO USE IT Do not put essential application data in headers. If the client needs the data to function correctly, it belongs in the response body. Headers are for metadata, not primary content. Also, if you need to return a completely different response type, like a file or a stream, you should return a FileResponse or StreamingResponse object directly, which has its own methods for setting headers.

ONE CANONICAL EXAMPLE This endpoint returns user data but also sets a custom header for tracing the request.

from fastapi import FastAPI, Response

app = FastAPI()

@app.get("/users/me") def get_current_user(response: Response): # Imagine a unique ID was generated for this request request_trace_id = "abc-123-xyz-789" response.headers["X-Request-Trace-ID"] = request_trace_id return {"user_id": "fido", "email": "fido@example.com"}

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.