Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Header Parameter Models

If you have a group of relatedheader parameters, you can create aPydantic model to declare them.

This would allow you tore-use the model inmultiple places and also to declare validations and metadata for all the parameters at once. 😎

Note

This is supported since FastAPI version0.115.0. 🤓

Header Parameters with a Pydantic Model

Declare theheader parameters that you need in aPydantic model, and then declare the parameter asHeader:

fromtypingimportAnnotatedfromfastapiimportFastAPI,HeaderfrompydanticimportBaseModelapp=FastAPI()classCommonHeaders(BaseModel):host:strsave_data:boolif_modified_since:str|None=Nonetraceparent:str|None=Nonex_tag:list[str]=[]@app.get("/items/")asyncdefread_items(headers:Annotated[CommonHeaders,Header()]):returnheaders
🤓 Other versions and variants

Tip

Prefer to use theAnnotated version if possible.

fromfastapiimportFastAPI,HeaderfrompydanticimportBaseModelapp=FastAPI()classCommonHeaders(BaseModel):host:strsave_data:boolif_modified_since:str|None=Nonetraceparent:str|None=Nonex_tag:list[str]=[]@app.get("/items/")asyncdefread_items(headers:CommonHeaders=Header()):returnheaders

FastAPI willextract the data foreach field from theheaders in the request and give you the Pydantic model you defined.

Check the Docs

You can see the required headers in the docs UI at/docs:

Forbid Extra Headers

In some special use cases (probably not very common), you might want torestrict the headers that you want to receive.

You can use Pydantic's model configuration toforbid anyextra fields:

fromtypingimportAnnotatedfromfastapiimportFastAPI,HeaderfrompydanticimportBaseModelapp=FastAPI()classCommonHeaders(BaseModel):model_config={"extra":"forbid"}host:strsave_data:boolif_modified_since:str|None=Nonetraceparent:str|None=Nonex_tag:list[str]=[]@app.get("/items/")asyncdefread_items(headers:Annotated[CommonHeaders,Header()]):returnheaders
🤓 Other versions and variants

Tip

Prefer to use theAnnotated version if possible.

fromfastapiimportFastAPI,HeaderfrompydanticimportBaseModelapp=FastAPI()classCommonHeaders(BaseModel):model_config={"extra":"forbid"}host:strsave_data:boolif_modified_since:str|None=Nonetraceparent:str|None=Nonex_tag:list[str]=[]@app.get("/items/")asyncdefread_items(headers:CommonHeaders=Header()):returnheaders

If a client tries to send someextra headers, they will receive anerror response.

For example, if the client tries to send atool header with a value ofplumbus, they will receive anerror response telling them that the header parametertool is not allowed:

{"detail":[{"type":"extra_forbidden","loc":["header","tool"],"msg":"Extra inputs are not permitted","input":"plumbus",}]}

Disable Convert Underscores

The same way as with regular header parameters, when you have underscore characters in the parameter names, they areautomatically converted to hyphens.

For example, if you have a header parametersave_data in the code, the expected HTTP header will besave-data, and it will show up like that in the docs.

If for some reason you need to disable this automatic conversion, you can do it as well for Pydantic models for header parameters.

fromtypingimportAnnotatedfromfastapiimportFastAPI,HeaderfrompydanticimportBaseModelapp=FastAPI()classCommonHeaders(BaseModel):host:strsave_data:boolif_modified_since:str|None=Nonetraceparent:str|None=Nonex_tag:list[str]=[]@app.get("/items/")asyncdefread_items(headers:Annotated[CommonHeaders,Header(convert_underscores=False)],):returnheaders
🤓 Other versions and variants

Tip

Prefer to use theAnnotated version if possible.

fromfastapiimportFastAPI,HeaderfrompydanticimportBaseModelapp=FastAPI()classCommonHeaders(BaseModel):host:strsave_data:boolif_modified_since:str|None=Nonetraceparent:str|None=Nonex_tag:list[str]=[]@app.get("/items/")asyncdefread_items(headers:CommonHeaders=Header(convert_underscores=False)):returnheaders

Warning

Before settingconvert_underscores toFalse, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores.

Summary

You can usePydantic models to declareheaders inFastAPI. 😎


[8]ページ先頭

©2009-2026 Movatter.jp