- FastAPI - Discussion
- FastAPI - Useful Resources
- FastAPI - Quick Guide
- FastAPI - Deployment
- FastAPI - Mounting Flast App
- FastAPI - Middleware
- FastAPI - Mounting A Sub-App
- FastAPI - FastAPI Event Handlers
- FastAPI - Websockets
- FastAPI - Using GraphQL
- FastAPI - Using MongoDB
- FastAPI - SQL Databases
- FastAPI - Crud Operations
- FastAPI - CORS
- FastAPI - Dependencies
- FastAPI - Nested Models
- FastAPI - Response Model
- FastAPI - Header Parameters
- FastAPI - Cookie Parameters
- FastAPI - Uploading Files
- FastAPI - Accessing Form Data
- FastAPI - HTML Form Templates
- FastAPI - Static Files
- FastAPI - Templates
- FastAPI - Request Body
- FastAPI - Pydantic
- FastAPI - Parameter Validation
- FastAPI - Query Parameters
- FastAPI - Path Parameters
- FastAPI - Rest Architecture
- FastAPI - IDE Support
- FastAPI - Type Hints
- FastAPI - Uvicorn
- FastAPI - OpenAPI
- FastAPI - Hello World
- FastAPI - Introduction
- FastAPI - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
FastAPI - Header Parameters
In order to read the values of an HTTP header that is a part of the cpent request, import the Header object from the FastAPI pbrary, 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.
