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.

Use of Cookies

  • Session management: Cookies can store session IDs to track a user’s session on a website.
  • User authentication: Cookies may contain authentication tokens or user information to authenticate and remember users.
  • Personalization: Cookies can store your preferences and settings.

Some Concepts Related to Cookies

Before Setting Cookies in FastAPI, let us discuss and get familiar with some of the terminology and concepts:

Response: Response is a class present in the FastAPI module which is used to customize the HTTP response that is sent to the client by the server. It consists of various attributes such as status_code that can be used to set the status of the HTTP response as well as methods send_json for sending JSON data to the client.

set_cookie: set_cookie is a method present in the Response class that can be used to set the cookie on the user’s browser. It takes a key and value. The key is used to identify the cookie and the value is the information that is used by the server.

response.set_cookie(key="cookie_key", value="cookie_value")

Response Parameter: You can define a parameter of type Response in the decorator function when declaring an endpoint. The response object can then be used to set the cookie. The fastAPI will use this temporary response object to set the various HTTP response information setter by using its methods and attributes and then the HTTP response is send to the client.

def func(response: Response)

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

...