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.
You can see the cookie being set in the browser using the developer tool.