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
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read