Skip to content
tezvyn:
Menu

FastAPI: Setting Custom Response Headers

Source: fastapi.tiangolo.comHardHow cards are made

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"}

Interview question

In FastAPI, when you need to add a custom HTTP header like a trace ID to a JSON response without altering the response body, what is the correct method?

  • a.Return a fastapi.Response object directly, populating its content and headers.
  • b.Declare a Response parameter in the path operation, set headers on its .headers attribute, and return your data normally.Correct
  • c.Include the custom header as a top-level key-value pair within the JSON data returned by the endpoint.
  • d.Define a custom HTTPResponse class that inherits from JSONResponse and overrides its headers attribute.
Why?

The card states to declare a Response parameter, set headers on its .headers attribute, and then return your data normally. Returning the Response object directly (option A) is explicitly warned against as a 'footgun' because FastAPI automatically merges the headers with your returned data.

Just read this? Test yourself on what you have been reading.

Read the original → fastapi.tiangolo.com

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.

See open roles