skip to content

In a FastAPI create endpoint answering 201 with a Location header, how do you set status, headers and cookies yet keep response_model filtering?

level: middleimportance: should knowfreq 40%

answer

  1. decorator argument for the usual code
  2. a temporary Response object
  3. declare it like any parameter
  4. last write wins

basics

~10 s

Put status_code=status.HTTP_201_CREATED on the decorator, declare a parameter typed Response, set response.headers["Location"] or call response.set_cookie on it, and return plain data. FastAPI copies the status, headers and cookies into the filtered response.

solid answer

~40 s

The route's normal status goes on the decorator: `status_code=status.HTTP_201_CREATED`, which is also what the docs show. For headers and cookies I declare a parameter annotated `Response`. FastAPI hands in a temporary response; I set `response.headers["Location"] = f"/articles/{slug}"` or call `response.set_cookie(...)` and return the model as usual. FastAPI then validates and filters the data with the return type or `response_model` and copies the status, headers and cookies into the response it builds. Setting `response.status_code` on that parameter overrides the decorator's code, which suits an upsert that answers 201 only when it created something. Dependencies can declare the same parameter; the last write wins. The one trap: if the function returns its own `Response`, the parameter is ignored.

code

python · 32 lines
python
from fastapi import FastAPI, Response, status
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()


class Article(BaseModel):
    slug: str
    title: str


ARTICLES: dict[str, Article] = {}


@app.post("/articles", status_code=status.HTTP_201_CREATED)
def create_article(article: Article, response: Response) -> Article:
    ARTICLES[article.slug] = article
    response.headers["Location"] = f"/articles/{article.slug}"
    return article


@app.delete("/articles/{slug}", status_code=status.HTTP_204_NO_CONTENT)
def delete_article(slug: str) -> None:
    ARTICLES.pop(slug, None)


client = TestClient(app)
r = client.post("/articles", json={"slug": "intro", "title": "Intro"})
print(r.status_code, r.headers["location"], r.json())
r = client.delete("/articles/intro")
print(r.status_code, repr(r.content))

go deeper

for a junior

Recall that status_code goes on the decorator and that fastapi.status holds named constants such as HTTP_201_CREATED.

for a middle

Explain the temporary Response parameter: what FastAPI copies from it, why filtering still runs, and which status wins when several places set one.

for a senior

Catch a dependency's status write that silently overrides the decorator's code, and harden cookie flags explicitly instead of trusting set_cookie's defaults.

for a principal

Set a convention for runtime status changes so the documented status codes and the real ones do not drift apart across a large API.

## The scenario A **create endpoint**, `POST /articles`, should answer **201 Created** with a `Location` header pointing at the new article, and with a body filtered to the public fields of the article model. FastAPI has a separate tool for each part, and the point of the question is to use them without giving up response filtering. ## The default status: the decorator's `status_code` `status_code` is an argument of the **decorator** (`@app.post(...)`), not of your function. It: - sets the status sent when nothing overrides it; - documents that code in the OpenAPI schema, so Swagger UI shows "201" for the route. It accepts an int or an `IntEnum` such as `http.HTTPStatus`; most code uses the named constants in `fastapi.status` (`status.HTTP_201_CREATED`), which is Starlette's `status` module re-exported. They hold the same number and exist for autocompletion and readability. ## Headers, cookies and status per request: a `Response` parameter Declare a parameter whose type is `Response` (from `fastapi`). FastAPI recognises the type and passes in a **temporary response object**, created for this request with no status of its own. You can: 1. set a header: `response.headers["Location"] = "/articles/intro"`; 2. set a cookie: `response.set_cookie("draft_id", value, httponly=True)`; 3. change the status: `response.status_code = status.HTTP_201_CREATED`. Then **return plain data as usual**. FastAPI validates and filters it with the return type or `response_model`, builds the real response, and copies the temporary object's status code, headers and cookies into it. That is why this pattern keeps filtering, while returning a `JSONResponse` yourself does not. Precedence rules worth stating: - A status set on the `Response` parameter **overrides** the decorator's `status_code`. The upsert in FastAPI's docs uses this: decorator `status_code=200`, and the creating branch sets 201. - Dependencies may declare the same `Response` parameter. All of them receive the same temporary object for the request, so **the last one to set a value wins**. - If the function returns a `Response` of its own, the temporary object is **discarded**: set headers and cookies on the object you return. `set_cookie` follows Starlette's defaults: `path="/"`, `samesite="lax"`, and `httponly` and `secure` both `False`. For a session-like cookie, set `httponly=True` and `secure=True` explicitly rather than assuming them. ## Walking through `POST /articles` For the create endpoint in the example below, one request goes like this: 1. FastAPI reads the JSON body into an `Article` and creates the temporary response, with no status set. 2. The function stores the article and writes `Location: /articles/intro` onto the temporary response. 3. The function returns the `Article`. FastAPI validates it against the return type and serializes only the declared fields. 4. FastAPI builds the real response. Its status is the temporary object's status if one was set, otherwise the decorator's 201. 5. FastAPI appends the temporary object's headers, including `Location` and any `Set-Cookie`, and sends the response. Nothing in this flow requires building a response by hand, and the docs still show the 201 and the article schema. ## Status codes without a body Some codes forbid a body: anything below 200, plus 204 and 304 (FastAPI also treats 205 this way). FastAPI enforces this in two places: | Situation | What FastAPI does | |---|---| | A `response_model` or a non-`None` return type declared together with `status_code=204` | refuses at route registration: "Status code 204 must not have a response body" | | A route with `status_code=204`, no declared type, that returns plain data | sends the status with an empty body | | `-> None` return type with `status_code=204` | allowed since 0.117; empty body | | `-> None` with the default 200 | sends `null` as a JSON body | So a delete endpoint is written `@app.delete("/articles/{slug}", status_code=status.HTTP_204_NO_CONTENT)` with `-> None`. ## Documenting more than one status The schema shows the decorator's `status_code` only. A 201 chosen at runtime through the `Response` parameter, or through a returned `JSONResponse(status_code=201, ...)`, is not in the docs; describing extra responses is done with the decorator's `responses` argument, which belongs with OpenAPI customisation. ## Defender's notes on headers - Build `Location` from values you created (the new slug or id), not from request input echoed back. - A browser script can read a custom response header cross-origin only if CORS exposes it; that is configured in the CORS middleware, not here.

  • In FastAPI, what happens if a path operation declares status_code=201 and a dependency sets response.status_code = 202?
    The client gets 202. A status set on the temporary `Response` parameter, by the endpoint or any dependency, overrides the decorator's `status_code`. The schema still documents 201, because it is built from the decorator, so a runtime override like this should be rare and documented separately.
  • In FastAPI, why does a delete route with -> None and no status_code send a body?
    Without `status_code=204`, the route answers 200 and FastAPI serializes the `None` return as JSON `null`. Only a status that forbids a body, such as 204, makes FastAPI send an empty body. Declaring `status_code=status.HTTP_204_NO_CONTENT` with `-> None` is the supported form since 0.117.

  • Passing status_code as an argument of the path operation function
  • Returning JSONResponse just to add a Location header to a 201
  • Expecting set_cookie to default to httponly=True and secure=True
  • Believing a runtime status change appears in the generated docs
  • Thinking the decorator's status_code beats one set on the Response parameter

Assumes FastAPI 0.143; a None return type on a bodiless route such as a 204 delete has been accepted since 0.117.