For example imagine that we have two endpoints:
class FooRequest(BaseModel):
data: str
@router.post("/foo/", response_model=FooRequest)
async def foo_view(data: FooRequest) -> FooRequest:
...
@router.get("/bar/", response_model=FooRequest)
async def bar_view(data: str = Query(..., description="Data param")) -> FooRequest:
...
In swagger UI /bar/ endpoint will have properly documented query param and /foo/ will have some abstract example of post body without any description.
So how can I document post body model?
You can declare an example for a Pydantic model using Config and schema_extra.
class FooRequest(BaseModel):
data: str
class Config:
schema_extra = {
"FooRequest": {
"name": "Foo Request",
"description": "Data param",
}
}
Also with Field you declare extra info for your JSON Schema.
from pydantic import Field
...
class FooRequest(BaseModel):
data: str = Field(..., example="Data param for Foo Request")
description: Optional[str] = Field(None, example="Description for Foo")
The same way you can pass extra info to Field, you can do the same with Path, Query, Body, etc.
For example, you can pass an example for a body request to Body:
from fastapi import Body
...
class FooRequest(BaseModel):
data: str
@router.post("/foo/", response_model=FooRequest)
async def foo_view(data: FooRequest = Body(
...,
example={
"name": "Foo Request",
"description": "data param",
},
),
) -> FooRequest: