Getting Cookies in FastAPI
Cookie parameter is used to get the cookie sent by the client to the server in the HTTP request. To use the cookie parameter in the decorator function you first need to import Cookie
from fastapi import Cookie
Now you can use it to get the cookie sent by the client in the decorator function as shown below :
@app.get("/cookie")
def func(get_cookie_key : Annotated[str | None, Cookie()] = None):
When the user sends an HTTP request to the client at the “/cookie” endpoint the server first parse the cookie “get_cookie_key” and send it as a parameter to the decorator function func. Copy the below code and paste it in app.py file created above :
Python3
@app .get( "/cookie" ) def func(gfg_cookie_key : Annotated[ str | None , Cookie()] = None ): return { "gfg_cookie" : gfg_cookie_key} |
Copy the below URL and paste it in browser
http://127.0.0.1:8000/cookie
When you hit the above url the browser sends the HTTP request to the server along the Cookies that is set by the server previously. When the request hits the server the server then parse the cookies sent by the browser and get the value of the ‘gfg_cookie_key’ and pass it to the decorator function defined for the “/cookie” endpoint. The server then just returns the cookie value as the response.
Contact Us