Mutate response metadata through dependency injection
A handler needs to add a cookie or header while returning ordinary data.
FastAPI · Class
FastAPI's Response class represents an HTTP response that can be injected to modify headers or cookies, or constructed and returned directly. Its constructor controls content, status, headers, media type, and background work.
Response is the base response type that you can inject into a path operation or dependency to modify outgoing headers and cookies, or instantiate and return directly. Its constructor stores the status code, optional media type, background task, rendered body, and initialized headers; direct returns bypass FastAPI's normal data conversion.
Response(content=None, status_code=200, headers=None, media_type=None, background=None)| Name | Type | Description |
|---|---|---|
content | Any = None | Response body content, rendered into the response body. |
status_code | int = 200 | HTTP status code. |
headers | Mapping[str, str] | None = None | Mapping of response header names to values. |
media_type | str | None = None | Optional response media type. |
background | BackgroundTask | None = None | Optional background task run after the response. |
An HTTP response object containing rendered content, status, headers, media type, and optional background work.
from fastapi import Response.from fastapi import FastAPI, Response
app = FastAPI()
@app.get("/health")
def health(response: Response):
response.set_cookie(key="checked", value="true")
return {"ok": True}Inject Response to add a cookie while allowing FastAPI to produce the normal response.
A handler needs to add a cookie or header while returning ordinary data.
An endpoint must emit explicit body content, status, or media type.
A response needs post-send background work configured at construction time.
Response is the base response class for FastAPI responses. It can be injected into a path operation or dependency so the handler can set response data such as headers or cookies.
Follow-up: How would you return a custom status and media type? Instantiate Response with content, status_code, headers, and media_type, then return that instance.
The constructor accepts content, status_code, headers, media_type, and background. It renders the content into the body and initializes headers during construction.
Follow-up: What happens if content is omitted? The default is None, which is passed through the response's rendering process.
Returning a Response instance sends it directly, so FastAPI does not perform normal data conversion. This also means response-model conversion and automatic response documentation do not apply in the usual way.
Follow-up: When should a response model be preferred? Prefer it when you want Pydantic serialization and generated OpenAPI response information.
BackgroundTaskJSONResponseHTMLResponsePlainTextResponseStreamingResponseRedirectResponse