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.

“/cookie” endpoint



FastAPI – Cookie Parameters

FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this beginner-friendly guide, we’ll walk you through the steps on how to use Cookie in FastAPI.

Similar Reads

What are Cookies?

Cookies are pieces of data stored on the client browser by the server when the user is browsing the web page. Multiple cookies can be stored on the user’s browser by the server during the session. Cookies can be of different types such as session cookies, persistent cookies, etc....

Setting Cookies in FastAPI

Create a folder named ‘gfg_fastapi’ and create a file named app.py and copy paste the below code:...

Getting Cookies in FastAPI

...