SoFunction
Updated on 2025-04-08

Two ways to obtain request header information using FastAPI

http request header

The HTTP request header is an important part of HTTP requests. It contains various meta information about the request, which exists in the form of key-value pairs, providing additional information for the server to process the request. The following is a brief explanation from the aspects of functions, common request headers, examples, etc.

  1. effect: It can inform the server about the client, such as client type, supported content type, cache policy, etc., so that the server can correctly process the request based on this information and return a suitable response. For example, through the request headerUser - Agent, The server can identify whether the client is a browser, mobile application or other tool, thereby returning the adapted content.

  2. Common request headers

    • User-Agent: Contains relevant information about the client that issued the request, such as browser type, version, operating system, etc. For exampleMozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36, which means that this is a request from Windows 10 system and using Chrome browser.
    • Content-Type: Used to specify the media type of the request body, common ones areapplication/jsonIndicates that the request body is JSON format data.application/x-www-form-urlencodedRepresents form data.
    • Accept: Tell the server client that the response content type can be accepted, such asAccept: text/htmlIndicates that the client expects to receive a response in HTML format.
  1. Example: In a simple login request, there may beContent-Type: application/json, indicating that the request body is JSON format data, which may contain information such as username and password;User-AgentIndicates the relevant information of the client, the server performs corresponding processing based on this information, such as verifying the login information and returning a response in a suitable format.

In FastAPI, getting HTTP request headers can help developers better understand the source and features of the request, thereby achieving more flexible and personalized business logic, such asUser - AgentDifferent page renderings are performed according toContent - TypeCorrectly parse the request body, etc.

In FastAPI, there are many ways to obtain request header information. The following is a detailed introduction to two common methods and explain them in combination with sample code.

Method 1: Use the Request object

RequestObjects are objects in FastAPI representing HTTP requests, through which they can access various parts of the request, including the request header. You can inject it into the routing handler functionRequestObject, then useheadersAttribute to get request header information.

Sample code

from fastapi import FastAPI, Request

app = FastAPI()

@("/get_headers_with_request")
async def get_headers_with_request(request: Request):
    # Get all request header information    all_headers = dict()
    # Get specific request header information, such as 'User-Agent'    user_agent = ('User-Agent')

    return {
        "all_headers": all_headers,
        "User-Agent": user_agent
    }

Code explanation

  • Import the necessary modules: ImportFastAPIandRequest

  • Create a FastAPI application instanceapp = FastAPI()

  • Define routing processing functions

    • Inject in function parametersRequestObject.
    • useGet all request header information and convert it into a dictionary form.
    • use('User - Agent')Get specific request header information.
  1. Return result: Return all request header information and specific request header information in JSON format.

Method 2: Use parameter dependency injection

FastAPI supports declaring request header parameters directly in the parameters of the routing processing function. By specifying the parameter name and type, FastAPI will automatically extract the corresponding value from the request header.

Sample code

from fastapi import FastAPI, Header

app = FastAPI()

@("/get_headers_with_header")
async def get_headers_with_header(user_agent: str = Header(None), custom_header: str = Header(None)):
    return {
        "User-Agent": user_agent,
        "Custom-Header": custom_header
    }

Code explanation

  1. Import the necessary modules: ImportFastAPIandHeader
  2. Create a FastAPI application instanceapp = FastAPI()
  3. Define routing processing functions
    • Use in function parametersHeaderDependency injection request header parameters.
    • user_agent: str = Header(None)Indicates extracting from the request headerUser - AgentThe value of the field and assign it touser_agentVariable. If the field does not exist in the request header, the default value isNone
    • same,custom_header: str = Header(None)Used to extract custom request headersCustom - Headervalue.
  4. Return result: Return the extracted request header information in JSON format.

Running example

Save the above code as, and then run the following command in the terminal to start the FastAPI application:

uvicorn main:app --reload

After the startup is successful, you can use tools (such ascurlor Postman) sends a request to the corresponding route to view the returned request header information. For example, usecurlSend a request:

curl -H "User-Agent: MyCustomUserAgent" -H "Custom-Header: MyCustomValue" http://127.0.0.1:8000/get_headers_with_header

This way you can see that the request header is properly extracted and returned.

Final summary

In FastAPI development, it is crucial to obtain request headers. The Request object method provides comprehensive and flexible operations, allowing overall processing and analysis of all request headers, and is suitable for scenarios where a comprehensive understanding of the request header situation is required. The parameter dependency injection rule is concise and intuitive, and the code is easier to read, suitable for situations where you know exactly which specific request headers you need to get. Developers can choose appropriate methods based on specific needs. By rationally using these two methods, they can efficiently process HTTP request header information, improving the development efficiency and functionality of FastAPI applications.

The above is the detailed content of two methods for python to use FastAPI to obtain request header information. For more information about obtaining information by python FastAPI, please follow my other related articles!