Setting Cookies in FastAPI

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

In the below code we first created the app using FastAPI class and the defined the “/” endpoint which will have a response parameter. The response instance is used to set the cookie using the ‘set_cookie’ method present in it.

Python3




from fastapi import FastAPI, Response, Cookie
from typing import Annotated
app = FastAPI()
 
@app.get("/")
def func(response : Response):
    response.set_cookie(key = "gfg_cookie_key", value = "gfg_cookie_value")
    return {"message" : "Cookie is set on the browser"}


Running the Application

To run the above application copy paste the below command and run in terminal

python -m uvicorn app:app --reload

Output

The server will be up and running and will be available at the below URL

http://127.0.0.1:8000

When you open the above url on web browser of your choice, the “/” endpoint defined in the application is hit and the func function is executed which set the cookie on the browser.

Application “/” endpoint

You can see the cookie being set in the browser using the developer tool.

Cookies

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

...

Contact Us