I'm making a function and class for it with POST
method.
Since I use FastAPI, it automatically generates API docs (using OpenAPI specification and Swagger UI), where I can see the function's description or example data there.
My class and function are like below:
from pydantic import BaseModel, Field
from typing import Optional, List
@app.post("/user/item")
def func1(args1: User, args2: Item):
...
class User(BaseModel):
name: str
state: List[str]
class Config:
schema_extra = {
"example": {
"name": "Mike",
"state": ["Texas", "Arizona"]
}
}
class Item(BaseModel):
_id: int = Field(..., example=3, description="item id")
Through schema_extra
and example
attribute in Field
, I can see the example value in Request body
of function description.
It shows like
{
"args1": {
"name": "Mike",
"state": ["Texas", "Arizona"] # state user visits. <-- I'd like to add this here or in other place.
},
"args2: {
"_id": 3 <-- Here I can't description 'item id'
}
}
However, I'd like to add description or comments to example value
, like # state user visits above.
I've tried to add description
attribute of pydantic Field
, but I think it shows only for parameters of get method.
Is there any way to do this? Any help will be appreciated.
You are trying to pass "comments" inside the actual JSON
payload that will be sent to the server. Thus, such an approach wouldn't work. The way to add description
to the fields is as shown below. Users/you can see the descriptions/comments, as well as the examples provided, by expanding the corresponding JSON schema of a Pydantic model (e.g., "User") under "Schemas" (at the bottom of the page) when visting OpenAPI at http://127.0.0.1:8000/docs, for instance. Or, by clicking on "Schema", next to "Example Value", above the example given in the "Request Body".
class User(BaseModel):
name: str = Field(..., description="Add user name")
state: List[str] = Field(..., description="State user visits")
class Config:
schema_extra = {
"example": {
"name": "Mike",
"state": ["Texas", "Arizona"]
}
}
Alternatively, you could use Body
field in your endpoint, allowing you to add a description that is shown under the example in the "Request body". As per the documentation:
But when you use
example
orexamples
with any of the other utilities (Query()
,Body()
, etc.) those examples are not added to the JSON Schema that describes that data (not even to OpenAPI's own version of JSON Schema), they are added directly to the path operation declaration in OpenAPI (outside the parts of OpenAPI that use JSON Schema).
You could add multiple examples (with their associated descriptions), as described in the documentation. Example below:
@app.post("/user/item")
async def update_item(
user: User = Body(
...,
examples={
"normal": {
"summary": "A normal example",
"description": "**name**: Add user name. **state**: State user vistis. ",
"value": {
"name": "Mike",
"state": ["Texas", "Arizona"]
},
}
}
),
):
return {"user": user}