Tips and Tricks

FastAPI

FastAPI - set cookie when returning a response


FastAPI tip:

You can set a cookie on the response by using .set_cookie(). Response must be added as a view argument.

https://fastapi.tiangolo.com/advanced/response-cookies/

👇

from fastapi import FastAPI, Response

app = FastAPI()


@app.post("/session/")
def cookie(response: Response):
    response.set_cookie(key="mysession", value="1242r")
    return {"message": "Wanna cookie?"}