- FastAPI - Discussion
- FastAPI - Useful Resources
- FastAPI - Quick Guide
- FastAPI - Deployment
- FastAPI - Mounting Flast App
- FastAPI - Middleware
- FastAPI - Mounting A Sub-App
- FastAPI - FastAPI Event Handlers
- FastAPI - Websockets
- FastAPI - Using GraphQL
- FastAPI - Using MongoDB
- FastAPI - SQL Databases
- FastAPI - Crud Operations
- FastAPI - CORS
- FastAPI - Dependencies
- FastAPI - Nested Models
- FastAPI - Response Model
- FastAPI - Header Parameters
- FastAPI - Cookie Parameters
- FastAPI - Uploading Files
- FastAPI - Accessing Form Data
- FastAPI - HTML Form Templates
- FastAPI - Static Files
- FastAPI - Templates
- FastAPI - Request Body
- FastAPI - Pydantic
- FastAPI - Parameter Validation
- FastAPI - Query Parameters
- FastAPI - Path Parameters
- FastAPI - Rest Architecture
- FastAPI - IDE Support
- FastAPI - Type Hints
- FastAPI - Uvicorn
- FastAPI - OpenAPI
- FastAPI - Hello World
- FastAPI - Introduction
- FastAPI - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
FastAPI - Cookie Parameters
A cookie is one of the HTTP headers. The web server sends a response to the cpent, in addition to the data requested, it also inserts one or more cookies. A cookie is a very small amount of data, that is stored in the cpent’s machine. On subsequent connection requests from the same cpent, this cookie data is also attached along with the HTTP requests.
The cookies are useful for recording information about cpent’s browsing. Cookies are a repable method of retrieving stateful information in otherwise stateless communication by HTTP protocol.
In FastAPI, the cookie parameter is set on the response object with the help of set_cookie() method
response.set_cookie(key, value)
Example
Here is an example of set_cookie() method. We have a JSON response object called content. Call the set_cookie() method on it to set a cookie as key="usrname" and value="admin" −
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.post("/cookie/") def create_cookie(): content = {"message": "cookie set"} response = JSONResponse(content=content) response.set_cookie(key="username", value="admin") return response
To read back the cookie on a subsequent visit, use the Cookie object in the FastAPI pbrary.
from fastapi import FastAPI, Cookie app = FastAPI() @app.get("/readcookie/") async def read_cookie(username: str = Cookie(None)): return {"username": username}
Inspect these two endpoints in the Swagger API. There are these two routes "/cookies" and "/readcookie". Execute the create_cookie() function bound to "/cookies". The response is just the content, although the cookie is set.
When the read_cookie() function is executed, the cookie is read back and appears as the response. Also, not that the documentation identifies the user name as a cookie parameter.
Advertisements