Sling Academy
Home/FastAPI/FastAPI: How to extract request headers (2 approaches)

FastAPI: How to extract request headers (2 approaches)

Last updated: April 18, 2023

This concise, practical article will walk you through a couple of different ways to extract headers from an incoming request in FastAPI.

What are HTTP headers?

Headers are part of HTTP messages that pass additional information and metadata about the request or response. They consist of case-insensitive name-value pairs separated by a colon. For instance, a request message can use headers to indicate its preferred media formats, while a response can use headers to indicate the media format of the returned body. Headers can be grouped into different categories according to their contexts and how they are handled by proxies and caches.

Some common headers are:

  • User-Agent: identifies the client software that is making the request.
  • Referer: indicates the URL of the previous web page from which a link was followed.
  • Authorization: contains the credentials to authenticate a user-agent with a server.
  • Content-Type: indicates the MIME type of the body of the request or response.
  • Content-Length: indicates the size of the body in bytes.

Extracting request headers in FastAPI

Using the Request object directly

The easiest way to get headers from incoming requests is to use the Request object directly. You can import it from fastapi and declare it as a parameter in your path operation function. FastAPI will pass the request object to that parameter. Then you can access the headers attribute of the request object, which is a dictionary of header names and values.

The general syntax is:

some_header = request.headers.get("header name")

Real-world example:

import fastapi
from fastapi import Request

app = fastapi.FastAPI()

@app.get("/")
def home_route(request: Request):
    user_agent = request.headers.get("user-agent")
    authorization = request.headers.get("authorization")
    referer = request.headers.get("referer")
    
    print(f"User-Agent: {user_agent}")
    print(f"Authorization: {authorization}")
    print(f"Referer: {referer}")

    return {
        "message": "Welcome to Sling Academy"
    }

If a header doesn’t exist, the result will be None.

Using Header parameters

Another way is to use Header parameters in your path operation function, which will automatically convert the header name from underscore to hyphen and validate the type.

Example:

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/")
async def home_route(
        user_agent: str = Header(None),
        authorization: str = Header(None),
        referer: str = Header(None)):
    
    print("user_agent: ", user_agent)
    print("authorization: ", authorization)
    print("referer: ", referer)

    return {
        "message": "Welcome to Sling Academy",
    }

Both this approach and the previous one are concise and convenient. Choose from them the one you like to implement in your project.

Next Article: 3 Ways to Get User’s IP Address in FastAPI

Previous Article: Getting the Request Body in FastAPI

Series: FastAPI Request & Response Tutorials

FastAPI

You May Also Like

  • Popular useful built-in Jinja filters you should know
  • How to remove consecutive whitespace in rendered Jinja pages
  • How to format large numbers with thousand separators in Jinja template
  • How to format date time in Jinja templates
  • FastAPI + Jinja: How to create custom filters
  • How to pass variables from Python (FastAPI) to Jinja
  • How to decode Jinja response to string
  • How to create and use macros in Jinja
  • How to use namespace in Jinja
  • How to use if/ else in Jinja
  • How to use loops in Jinja
  • FastAPI + SQLAlchemy: Using cursor-based pagination
  • FastAPI: How to use macros in Jinja templates
  • Fixing Common Swagger UI Errors in FastAPI
  • FastAPI Error: 307 Temporary Redirect – Causes and Solutions
  • FastAPI Error: Expected UploadFile, received ‘str’
  • Resolving FastAPI ImportError: No Known Parent Package
  • FastAPI Error: No module named ‘pydantic_core._pydantic_core’
  • Resolving FastAPI 422 Error: Value is not a valid dict