FastAPI: Set Cookies Without Returning a Response Object
Inject a `Response` object into your endpoint to set cookies without manually building the whole response. Use this for session tokens while still returning data like a dict.
WHY IT EXISTS Often, an API endpoint needs to do two things: return a JSON body and set a cookie, like a session ID. Manually creating a Response object, setting the cookie, and then serializing your JSON body is cumbersome. FastAPI provides a more elegant way to handle this common pattern.
THE MENTAL MODEL Think of it as dependency injection for the response itself. You request a Response object as a parameter in your endpoint function. You then modify this object (e.g., set a cookie) but return your data as usual. FastAPI acts as a helper, merging your modifications into the final response it sends to the client.
HOW IT WORKS You declare a function parameter with the type hint Response, for example: def my_endpoint(response: Response):. FastAPI sees this, creates a temporary Response object, and passes it to your function. Inside, you can call methods like response.set_cookie(...). When your function finishes and returns its data (like a dictionary), FastAPI copies the cookies, headers, and status code from your temporary Response object to the final HTTP response it generates from your returned data.
WHEN TO USE IT This is the idiomatic FastAPI approach whenever you need to set a cookie, add a custom header, or change the status code while still returning a standard data structure like a dictionary or a Pydantic model. It cleanly separates the logic for creating the response body from setting response metadata.
WHEN NOT TO USE IT If you need to return a non-standard body, like a file stream or a custom HTML page, you should create and return a specific response class directly (e.g., FileResponse, StreamingResponse). In those cases, you would call set_cookie on the response object you are about to return, not on an injected one.
ONE CANONICAL EXAMPLE In an endpoint, you can add a response: Response parameter. Then you can call response.set_cookie(key="fakesession", value="some-value"). Even if your function returns a simple dictionary like {"message": "Cookie set!"}, FastAPI will ensure the final HTTP response includes both the JSON body and the Set-Cookie: fakesession=some-value; path=/; httponly header.
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.