Managing cookies
A cookie is a piece of information stored in the browser to pursue some purpose, such as login user authorization, web agent response generation, and session handling-related tasks. One cookie is always a key-value pair that are both string types.
FastAPI allows services to create cookies individually through the Response
library class from its fastapi
module. To use it, it needs to appear as the first local parameter of the service, but we do not let the application or client pass an argument to it. Using the dependency injection principle, the framework will provide the Response
instance to the service and not the application. When the service has other parameters to declare, the additional declaration should happen right after the declaration of the Response
parameter.
The Response
object has a set_cookie()
method that contains two required named parameters: the key, which sets the cookie name, and the value, which stores the cookie value. This method only generates one cookie and stores it in the browser afterward:
@app.post("/ch01/login/rememberme/create/") def create_cookies(resp: Response, id: UUID, username: str = ''): resp.set_cookie(key="userkey", value=username) resp.set_cookie(key="identity", value=str(id)) return {"message": "remember-me tokens created"}
The preceding create_cookies()
method shows us the creation of remember-me tokens such as userkey
and identity
for the remember-me authorization of our online academic discussion forum project.
To retrieve these cookies, local parameters that have the same name as the cookies are declared in the service method as str
types, since cookie values are always strings. As with Header
and Form
, the fastapi
module also provides a Cookie
function that is needed to initialize each declared cookie parameter variable. The Cookie()
function should always have the None
argument to set the parameters optionally, ensuring that the API method executes without problems whenever the headers are not present in the request transaction. The following access_cookie()
service retrieves all the remember-me authorization cookies created by the previous service:
@app.get("/ch01/login/cookies") def access_cookie(userkey: Optional[str] = Cookie(None), identity: Optional[str] = Cookie(None)): cookies["userkey"] = userkey cookies["identity"] = identity return cookies