Anyway, for the time being, define the form of the response from the API on the swagger screen of the Fast API, Articles for people who want to see sample responses.
I was like that, but I couldn't find such an article or blog, For the time being, I went through the fastapi official tutorial. I wrote it in the hope that it would help someone with the same purpose.
――Suppose that this type of data is returned as a response.
{
"Special_choco1": {
"Milk": "many",
"Quantity": 5,
"Cacao": "a little"
},
"Store":[
{
"Tokyo": "sibuya",
"Hokkaido": "sapporo",
"Osaka": "nanba"
}
]
}
--FastAPI version is 0.52.0
--Write in main.py Write in a file that writes app = FastAPI ().
-I'm sure there is another better way to write it.
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
class choco_model(BaseModel):
Milk: str
Quantity: int
Cacao: str
class Store_model(BaseModel):
Tokyo: str
Hokkaido: str
Osaka: str
class Special_choco(BaseModel):
Special_choco1: choco_model
Store: List[Store_model]
app = FastAPI()
@app.get("/api/v1/chocolate/{name}")
async def making_choco(name: str):
return #Omitted. An image of writing something that the JSON described in the premise changes.
Specify the model you want to define in response_model at the decorator. Then, it will be displayed in the Swagger's Example Value.
#Omission)
app = FastAPI()
@app.get("/api/v1/chocolate/{name}", response_model=Special_choco)
async def making_choco(name: str):
return #Omitted. An image of writing something that the JSON described in the premise changes.
Like this.
To display not only the type and data structure, but also what kind of value is returned Describe the data you want to display in the definition part in class Config as follows. Then, the concrete value will be displayed in the example value column.
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
class choco_model(BaseModel):
Milk: str
Quantity: int
Cacao: str
class Config:
schema_extra = {
"example": {
"Milk": "very lot",
"Quantity": 10,
"Cacao": "many",
}
}
class Store_model(BaseModel):
Tokyo: str
Hokkaido: str
Osaka: str
class Config:
schema_extra = {
"example": {
"Tokyo": "shibuya",
"Hokkaido": "sapporo",
"Osaka": "nishinari",
}
}
#Omission
It is displayed as follows.
The fastapi official tutorial has a lot of volume, but it is good to do it.
Recommended Posts