(2023.06.08 Thur @KLN HK)
FastAPI構建API/endpoint過程中建議使用pydantic包實現(xiàn)data validation,同時建議使用python enum實現(xiàn)元素枚舉拳喻。
在endpoint中添加example
實現(xiàn)這一endpoint需要若干步驟
- 預先定義Response Model和Request Model,以及需要在endpoint中展示的filter example
- 在入口函數(shù)的API/endpoint中添加response&request model
(2023.06.11 Sun @SZ 穎隆大廈)
具體案例如下:
在models.py
中通過pydantic的BaseModel定義Request Model和Response Model刷晋,以及filter example.
# models.py
from pydantic import BaseModel
from datetime import datetime
class RequestModel(BaseModel):
start_: str
end_: str
ids: list[str] = []
cons = 100
class ResponseModel(BaseModel):
res_count: int = 0
res1: list[dict] = []
res2: list[dict] = []
filter_examples = {
"example1": {
"summary": "example 1 - demo 1",
"description": "this is a description",
"value": {
"start_": "value1",
"end_": "value2",
"ids": ["value3"]
},
}
}
在FastAPI的入口文件main-api.py
中代碼如下
# main-api.py
from fastapi import FastAPI, Query, Body
from models import RequestModel, ResponseModel, filter_examples
from fastapi.openapi.docs import get_swagger_ui_html
app = FastAPI()
@app.post("/endpoint1/", tags=["show-examples"], response_model=ResponseModel)
async def func_ep1(requests_model: RequestModel=Body(examples=filter_examples)):
res = {'res_count': requests_model.cons, 'res1': [{"start_": requests_model.start_}],
'res2': [{"end_": requests_model.end_}]}
return res
@app.get("/docs")
def read_docs():
return get_swagger_ui_html(openapi_url="/openapi.json")
其中的@app.get("/docs")
部分設定swagger UI生均。
在endpoint1
的函數(shù)中定義requests_model
陪蜻,并將其中的值傳遞給返回結果邦马。
在endpoint中加入下拉列表
需要使用fastapi中的Query
方法。
在models.py
文件中加入Enum對象宴卖,給出下拉列表的元素滋将。
# models.py
from enum import Enum
class someClassEnum(str, Enum):
field_a = "a"
field_b = "b"
field_c = "c"
在入口文件中加入對應的endpoint
# main-api.py
from fastapi import FastAPI, Query, Body
from models import someClassEnum
app = FastAPI()
@app.get("/endpoint2", tags=["dropdown-list"])
async def func_ep2(data_field: someClassEnum = Query(someClassEnum.field_a)) -> dict:
return {"req_name": data_field.name, "req_value": data_field.value}
返回結果中有下拉列表
dropdown list in FastAPI