
- FastAPI Tutorial
- FastAPI - Home
- FastAPI - Introduction
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - Type Hints
- FastAPI - IDE Support
- FastAPI - Rest Architecture
- FastAPI - Path Parameters
- FastAPI - Query Parameters
- FastAPI - Parameter Validation
- FastAPI - Pydantic
- FastAPI - Request Body
- FastAPI - Templates
- FastAPI - Static Files
- FastAPI - HTML Form Templates
- FastAPI - Accessing Form Data
- FastAPI - Uploading Files
- FastAPI - Cookie Parameters
- FastAPI - Header Parameters
- FastAPI - Response Model
- FastAPI - Nested Models
- FastAPI - Dependencies
- FastAPI - CORS
- FastAPI - Crud Operations
- FastAPI - SQL Databases
- FastAPI - Using MongoDB
- FastAPI - Using GraphQL
- FastAPI - Websockets
- FastAPI - FastAPI Event Handlers
- FastAPI - Mounting A Sub-App
- FastAPI - Middleware
- FastAPI - Mounting Flast App
- FastAPI - Deployment
- FastAPI Useful Resources
- FastAPI - Quick Guide
- FastAPI - Useful Resources
- FastAPI - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
FastAPI - Header Parameters
In order to read the values of an HTTP header that is a part of the client request, import the Header object from the FastAPI library, and declare a parameter of Header type in the operation function definition. The name of the parameter should match with the HTTP header converted in camel_case.
In the following example, the "accept-language" header is to be retrieved. Since Python doesn’t allow "-" (dash) in the name of identifier, it is replaced by "_" (underscore)
from typing import Optional from fastapi import FastAPI, Header app = FastAPI() @app.get("/headers/") async def read_header(accept_language: Optional[str] = Header(None)): return {"Accept-Language": accept_language}
As the following Swagger documentation shows, the retrieved header is shown as the response body.

You can push custom as well as predefined headers in the response object. The operation function should have a parameter of Response type. In order to set a custom header, its name should be prefixed with "X". In the following case, a custom header called "X-Web-Framework" and a predefined header “Content-Language" is added along with the response of the operation function.
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.get("/rspheader/") def set_rsp_headers(): content = {"message": "Hello World"} headers = {"X-Web-Framework": "FastAPI", "Content-Language": "en-US"} return JSONResponse(content=content, headers=headers)
The newly added headers will appear in the response header section of the documentation.
