Open In App

FastAPI – Header Parameters

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  1. Request Headers: HTTP request is used in HTTP requests, but it is not related to the content of the message.
  2. 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:

  1. Security: Header parameters can help secure the API and block unauthorized access assing authentication and authorization tokens.
  2. 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.
  3. 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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads