FastAPI - Header Parameters
Last Updated :
06 Dec, 2023
FastAPI is the fastest-growing Python API development framework, It is easy to lightweight, and user-friendly and It is based on standard Python-type hints, which makes it easier to use and understand.
FastAPI supports header parameters, these are used to validate and process incoming API calls. In this article, you will learn everything you need to know about header parameters in FastAPI, request headers and response headers, how to add headers to the request function definition, how to provide custom response headers and explain with the help of examples. Lastly, the benefits of using header parameters. At the end of this article, you will have a solid understanding of header parameters, and how to implement them to set up a robust and secure REST API.
What is a Header Parameter?
Headers are pieces of information that are transmitted with the request and received with the response. So we can manipulate both in Fast API.
- Request Headers: HTTP request is used in HTTP requests, but it is not related to the content of the message.
- Response Headers: HTTP request is used in HTTP response, but it is not related to the content of the message.
So first of all, in Python, we can add a specific custom header to our function definition. Or actually, if we want an existing header, we can do that too. Just make sure it's not one of those headers that are automatically written or overwritten by the request if we make the request to the browser.
To use header parameters in FastAPI, use the Header() decorator. The decorator allows a parameter to be declared as a header parameter.
Adding headers in the request function definition:
from fastapi import FastAPI, Header
@app.get("/")
def root(custom_header: Optional[str] = Header(None)):
...
Note: Provide default value as header from FastAPI. Otherwise, it will be interpreted as a query parameter. The Optional[str], header type informs FastAPI that the custom_header parameter is optional. and Header(None)) tell the system that we are expecting a header for this parameter.
Note: We can attach as many headers as we want here to the response.
Header parameters in Fast API Examples
Authentication
This example shows how to use header parameters to authenticate users before accessing an API endpoint
For the /login endpoint, the parameter requires a username and password. If the username and password are valid, a message is displayed that login successful. If not, an HTTP status code 401 (Unauthorized).
Python3
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
# Test user database
user_db = {
"user123": "user@pswrd"
}
@app.post("/login/")
async def login(username: str = Header(None), password: str = Header(None)):
if username in user_db and password == user_db[username]:
return {"message": "Login successful"}
else:
raise HTTPException(status_code=401, detail="Authentication failed")
Output:
API versioning
This example shows how to use header parameters to implement API versioning:
Here the endpoints, /v1/resources/ and /v2/resources/, are tagged with their respective API versions. The api_version header parameter is used to specify the desired version. Based on the header value, the appropriate version of the resource is returned.
Python3
@app.get("/v1/resource/", tags=["v1"])
async def resource_v1(api_version: str = Header(None)):
if api_version == "1":
return {"message": "Resource for API version 1"}
else:
return {"message": "API version not supported"}
@app.get("/v2/resource/", tags=["v2"])
async def resource_v2(api_version: str = Header(None)):
if api_version == "2":
return {"message": "Resource for API version 2"}
else:
return {"message": "API version not supported"}
Output:
Language preference
This example shows how to use header parameters to implement language preference:
Endpoint / Greet Welcomes the user in his or her preferred language. The preferred_language header parameter is used to specify the language. If the provided language is supported, the corresponding greeting will be returned. If the language is not supported, a message is displayed indicating "Language is not supported".
Python3
@app.get("/greet/")
async def greet(preferred_language: str = Header(default="en")):
greetings = {
"en": "Hello!",
"es": "¡Hola!",
"fr": "Bonjour!",
"hi": "नमस्ते!"
}
if preferred_language in greetings:
return {"message": greetings[preferred_language]}
else:
return {"message": "Language not supported"}
Output:
Benefits of using Header Parameters
These are some of the benefits of using header parameters:
- Security: Header parameters can help secure the API and block unauthorized access assing authentication and authorization tokens.
- Performance: Header parameters are faster than query and path parameters because request body header parameters are more difficult for beginners to understand than request headers.
- Flexibility: Header parameters can be used to convey a variety of information to an API endpoint making them a flexible and powerful way to interact with APIs.
Similar Reads
FastAPI - Path Parameters
In this exploration, we'll dive into the realm of FastAPI Path Parameters, unraveling their pivotal role in constructing dynamic and versatile APIs. FastAPI stands out as a contemporary web framework celebrated for its speed, tailor-made for crafting APIs in Python 3.7 and beyond. Leveraging standar
4 min read
FastAPI - Query Parameters
In this article, we will learn about FastAPI Query Parameters, what are query parameters, what they do in FastAPI, and how to use them. Additionally, we will see examples of query parameters for best practices. What is FastAPI - Query Parameters?Query parameters stand as a formidable asset in bolste
6 min read
FastAPI - Cookie Parameters
FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this beginner-friendly guide, weâll walk you through the steps on how to use Cookie in FastAPI. What are Cookies?Cookies are pieces of data stored on the client browser by the server when the
4 min read
POST Query Parameters in FastAPI
FastAPI is a powerful and efficient Python web framework for building APIs with ease. For most of the applications getting data from a user is done through a POST request and this is a common task for developers is consume query parameters from POST requests. In this article, we'll explore the conce
4 min read
What is an API Header?
An API header is part of the HTTP request or response that carries additional information about the request. This information can include metadata such as content type, authentication tokens, and other custom data needed by the server or client to properly process the request or response. API header
5 min read
HTTP headers | Retry-After
HTTP headers are used to pass additional information with HTTP request or response. HTTP Retry-After header is an HTTP response header which indicates how long to wait before making another request. Depending on different status codes, there are different use cases of the Retry-After response header
2 min read
FastAPI - Response Model
FastAPI has garnered substantial recognition in the realm of web development, providing a swift and effective framework for constructing APIs using the renowned programming language, Python. The creation of APIs holds paramount importance in web development. A notable feature of FastAPI is its Respo
5 min read
HTTP headers | Save-Data
The Save-Data is a HTTP request-type header. It is used to indicate whether the client wants to turn on data saving mode or not. Here, data usage is measured in terms of cost and performance. The role of any browser is to provide optimized user experience by providing the highest possible level of p
2 min read
Return an Image in FastAPI
FastAPI is a Python web framework that makes it easy to build APIs quickly and efficiently. Returning an image is a common requirement in web development, and FastAPI makes it straightforward to do. another famous framework for doing the same is Flask, which is also Python-based. In this article, we
4 min read
HTTP headers | Accept-Ranges
The HTTP Accept-Ranges is the Response type header also the part of the ranges system. This header act as a marker that is used by the server to supports the partial request of the clients. The HTTP Accept-Ranges is useful when the client requests any particular portion of a huge file then this head
2 min read