fastapi_No.6_Get cookie and header parameters


Cookie is the data (usually encrypted) stored on the user's local terminal in order to identify the user's identity and perform Session tracking in the website, and the information is temporarily or permanently saved by the user's client computer.

set cookies

Usually, when the client accesses the server for the first time, the server will send some Cookie information to the client, and let the client computer store this information.
In fastapi, the server needs to use the Response class to set a cookie to the client.

from typing import Union
from fastapi import  FastAPI
app = FastAPI()
# Declare the request body type of a user class
from pydantic import BaseModel
class User(BaseModel):

# Import the Response class in fastapi to set cookie s
from fastapi import Response"/register/")
def createUser(user:User,response:Response):
    return {"result":"register successfully"}

if __name__ == "__main__":
    import uvicorn"main:app",host="localhost",port=8080,reload=True)

In this example, after the client sends a registration request to the server, the server sends two cookie s to the client.
The results of the postman demo are as follows:

Read cookie information

When the client accesses for the first time, the client often stores the cookie information. When accessing the server later, the server will read the relevant cookie information in the client.
To read cookie information in fastapi, you need to introduce the cookie function from the fastapi package.

# The demo server reads cookie information from the client
# Import the Cookie function in fastapi to represent cookies
from fastapi import Cookie
# It should be noted here that the name of the cookie definition needs to be the same as the key name of the cookie in the client! ! !
def get_items(item_id:int,userName:Union[str,None]=Cookie(default=None),pwd:Union[str,None]=Cookie(default=None)):
    return {

When reading the cookie in the client, it should be noted that the variable name of the cookie in the code must be the same as the key value in the client cookie! ! !

The results of testing in postman are as follows:


The request header contains some additional descriptions of many client requests, such as user-agent, content-type and other information.
The data in the request header is also stored in the form of key-value pairs. So when we want to get the request body content of a key, we must set the variable name of the corresponding key to receive the request header content.
In fastapi, you need to import the Header function to receive request header parameters.

Read single-value request header data

# Demonstrates getting information about request headers
# Import the Header function in fastapi to represent the header
from fastapi import Header
# Since the name of the key in the normal request header is User-Agent, how to use this as the variable name python thinks is illegal variable name
# Because of this conflict, user_agent will be regarded as User-Agent in fastapi.
# If you don't want to use this default conflict resolution, use convert_underscores=False in the Header function
def demo(user_agent:Union[str,None]=Header(None,convert_underscores=True),postman_token:Union[str,None]=Header(None)):

Here you need to know the meaning of the convert_underscores parameter in the Header function

The demonstration result of this example is as follows:

Get multi-value request header data

When obtaining multi-value request header data, the type of the variable corresponding to the corresponding request header needs to be set to the list type.

# Demonstrates getting a request header with multiple values
# To obtain request header information with multiple values, you need to set the type of the corresponding request header variable to a list type
from typing import List
def demos(x_token:Union[List[str],None]=Header(default=None,convert_underscores=True)):
    return {

The demonstration result is shown in the following figure:

Tags: Python Back-end FastAPI

Posted by ebm on Fri, 14 Oct 2022 23:43:19 +0530