← Back to FastAPI, page 4

fastapi-0063 · Easy fresher

How do you set response headers, cookies and a different status code from inside a FastAPI path function?

Add a parameter typed Response (from fastapi) to the function, then set response.headers[...], call response.set_cookie(...) or delete_cookie(), and change response.status_code. FastAPI merges these into the final response while still serialising your return value with response_model. To control the whole response, return a Response subclass (JSONResponse, RedirectResponse) yourself.

Full answer

Two approaches:

  1. Temporal Response parameter (keeps automatic JSON conversion and response_model filtering):
python
@app.get("/login")
def login(response: Response):
    response.set_cookie("session", token, httponly=True, secure=True, samesite="lax", max_age=3600)
    response.headers["X-Request-Source"] = "api"
    response.status_code = 201
    return {"ok": True}
  1. Return a response object: JSONResponse(content=..., status_code=202, headers={...}). This bypasses response_model validation and serialisation, so you must provide JSON-ready data (use jsonable_encoder for models and datetimes).

Cookies:

  • set_cookie(key, value, max_age, expires, path, domain, secure, httponly, samesite). Authentication cookies should be httponly=True (not readable by JavaScript), secure=True (HTTPS only) and samesite="lax" or "strict".
  • delete_cookie("session") sends an expired cookie (use the same path and domain).
  • Sign or encrypt cookies that carry data; browsers let users edit them.

Headers:

  • Use for Location on 201 responses, Cache-Control, ETag, Retry-After, Deprecation and Sunset, and custom X- headers. Header names are case-insensitive.
  • response.headers.append(...) for repeated headers; Set-Cookie can appear several times.

Status codes: set a default in the decorator (status_code=201) and override per request with response.status_code = 202 for conditional outcomes (for example 200 for update and 201 for create in an upsert).

Redirects: RedirectResponse(url, status_code=303) after form posts. CORS headers should come from CORSMiddleware, not by hand.

python
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient

app = FastAPI()
EXISTING = {"BCA-1"}


@app.put("/students/{roll_no}", status_code=200)
def upsert(roll_no: str, response: Response):
    if roll_no not in EXISTING:
        EXISTING.add(roll_no)
        response.status_code = 201
        response.headers["Location"] = f"/students/{roll_no}"
    return {"roll_no": roll_no}


@app.post("/login")
def login(response: Response):
    response.set_cookie("session", "abc123", httponly=True, secure=True, samesite="lax", max_age=3600)
    response.headers["Cache-Control"] = "no-store"
    return {"ok": True}


@app.post("/logout")
def logout(response: Response):
    response.delete_cookie("session")
    return {"ok": True}


@app.get("/accepted")
def accepted():
    return JSONResponse({"queued": True}, status_code=202, headers={"Retry-After": "5"})


c = TestClient(app)
r = c.put("/students/BCA-1")
print(r.status_code, r.headers.get("location"))
r = c.put("/students/BCA-9")
print(r.status_code, r.headers.get("location"))
r = c.post("/login")
print(r.headers["set-cookie"].split("; ")[0], "|", [a for a in ("HttpOnly", "Secure", "SameSite=lax") if a in r.headers["set-cookie"]], "|", r.headers["cache-control"])
print(c.post("/logout").headers["set-cookie"].split(";")[0], "(expired)")
r = c.get("/accepted")
print(r.status_code, r.headers["retry-after"], r.json())

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 200 None 201 /students/BCA-9 session=abc123 | ['HttpOnly', 'Secure', 'SameSite=lax'] | no-store session="" (expired) 202 5 {'queued': True}

Key points

  • Add a Response parameter to set headers, cookies and status
  • Returning a Response subclass bypasses response_model
  • Auth cookies: httponly, secure, samesite
  • delete_cookie must match path and domain
  • Set the default status in the decorator; override per request when needed

Common mistakes

  • Setting auth cookies without httponly, secure and samesite
  • Returning JSONResponse and expecting response_model to filter it
  • Deleting cookies with a different path or domain than they were set with
  • Setting CORS headers by hand instead of using CORSMiddleware

Follow-ups

  • How would you implement an upsert that returns 200 or 201?
  • How do you sign cookies?
  • What does jsonable_encoder do?

Tips

  • Show both approaches
  • List cookie flags
  • Mention Location on 201