🫐Unit 15: Header Parameters
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:
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 matchUser-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.
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.
Last updated