CS504070 - FastAPI Tutorials
  • 🧩CS504070 - FastAPI Tutorials
  • 🔎Unit 1: Python Type Hint
  • ⚙️Unit 2: Pydantic
  • 🔃Unit 3: Concurrency
  • 💾Unit 4: Install FastAPI
  • 🍉Unit 5: Hello World!
  • 🍌Unit 6: Path Parameters
  • 🍋Unit 7: Query Parameters
  • 🍊Unit 8: Request Body
  • 🍐Unit 9: Query Parameters and Validations
  • 🍎Unit 10: Path Parameters and Validations
  • 🍏Unit 11: Multiple Parameters
  • 🍇Unit 12: Request Body - List Fields and Nested Models
  • 🍓Unit 13: Data Types
  • 🍪Unit 14: Cookie Parameters
  • 🫐Unit 15: Header Parameters
  • 🍈Unit 16: Response Model - Return Type
  • 🍒Unit 17: Additional Models
  • 🥑Unit 18: Implementing JWT Authentication with FastAPI
  • ⚙️Appendix A
  • 🍭Appendix B
Powered by GitBook
On this page
  • Introduction
  • Header parameters
  • Features of Header parameters

Unit 15: Header Parameters

PreviousUnit 14: Cookie ParametersNextUnit 16: Response Model - Return Type

Last updated 1 year ago

Introduction

Header parameters in FastAPI are a way to receive HTTP headers in your endpoint functions. Headers can be used for passing additional information with HTTP requests and responses, such as authentication tokens, request metadata, or information about the client or server. FastAPI provides a simple and effective way to declare header parameters that you expect in your requests.


Header parameters

To declare header parameters, you use the Header class from fastapi. You specify header parameters as arguments to your path operation functions (like get, post, etc.), using default values from the Header class. This tells FastAPI that those arguments should be interpreted as header values.

Let's take a look at the below program:

from fastapi import FastAPI, Header
from typing import Annotated

app = FastAPI()

@app.get("/get-header/")
async def get_header(user_agent: Annotated[str | None, Header()] = None):
    return {"User-Agent": user_agent}

You can easily test the program by using Postman and a web browser, as shown in Fig. 1 and 2.

In this example, the get_header function expects a header parameter named user_agent. The Header class is used to define it as a header parameter with a default value of None, meaning it's optional. When a request is made to this endpoint, FastAPI will extract the User-Agent header from the request and pass it to the function as the user_agent argument.

Features of Header parameters

  • Automatic Conversion: FastAPI automatically converts header names from Python style (snake_case) to HTTP standard style (Camel-Case with hyphens), so user_agent in your function will match User-Agent in the HTTP header.

  • Optional Headers: By setting the default value of a header parameter to None or giving it a default value, you can make the header optional.

  • Required Headers: If you want to make a header required, just skip the default value. FastAPI will then expect that header to be present in the request, or it will return an error response.

  • Duplicate Headers: If you expect a header to be sent multiple times with different values, you can receive those values as a list by adding a type annotation of list[str] to your function argument, as shown in the below program.

from fastapi import FastAPI, Header
from typing import Annotated

app = FastAPI()

@app.get("/items/multiple/")
async def read_items_multiple(x_custom_header: Annotated[list[str], Header()] = None):
    return {"X-Custom-Header": x_custom_header}

Using header parameters can be particularly useful for APIs that require authentication, where an access token is sent as a header, or for any other scenario where you need to pass additional information that doesn't fit neatly into the path or query parameters.

🫐
Page cover image
Fig. 1. Using Postman to test API endpoint
Fig. 2. Using a web browser to test API endpoint