English 中文(简体)
FastAPI - Cookie Parameters
  • 时间:2024-11-03

FastAPI - Cookie Parameters


Previous Page Next Page  

A cookie is one of the HTTP headers. The web server sends a response to the cpent, in addition to the data requested, it also inserts one or more cookies. A cookie is a very small amount of data, that is stored in the cpent’s machine. On subsequent connection requests from the same cpent, this cookie data is also attached along with the HTTP requests.

The cookies are useful for recording information about cpent’s browsing. Cookies are a repable method of retrieving stateful information in otherwise stateless communication by HTTP protocol.

In FastAPI, the cookie parameter is set on the response object with the help of set_cookie() method


response.set_cookie(key, value)

Example

Here is an example of set_cookie() method. We have a JSON response object called content. Call the set_cookie() method on it to set a cookie as key="usrname" and value="admin"


from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.post("/cookie/")
def create_cookie():
   content = {"message": "cookie set"}
   response = JSONResponse(content=content)
   response.set_cookie(key="username", value="admin")
   return response

To read back the cookie on a subsequent visit, use the Cookie object in the FastAPI pbrary.


from fastapi import FastAPI, Cookie
app = FastAPI()
@app.get("/readcookie/")
async def read_cookie(username: str = Cookie(None)):
   return {"username": username}

Inspect these two endpoints in the Swagger API. There are these two routes "/cookies" and "/readcookie". Execute the create_cookie() function bound to "/cookies". The response is just the content, although the cookie is set.

FastAPI Cookie Parameters

When the read_cookie() function is executed, the cookie is read back and appears as the response. Also, not that the documentation identifies the user name as a cookie parameter.

FastAPI Cookie Parameters Advertisements