由於我想設計一個 API 完成不同種類發票的功能,包含
那要怎麼實作呢?首先是設計 Schema
這裡可以透過 Swagger UI 來做出下拉式選單,先來看看成品
透過 UI 介面,可以隨意切換不同的預設值,方便前後端進行溝通
而將不同的範例定義在 exmples 即可,格式如下
class Config:
examples = {
"example": {
"summary": "登錄紙本電子發票",
"value": {
"tag": "invoice_paper",
"user": {
"name": "小明",
"email": "test@example.com",
"phone": "0912345678",
},
"invoice": [
{
"invDate": "20230705",
"invNum": "AB12345678",
"random_number": "1234",
},
{
"invDate": "20230706",
"invNum": "AB12345679",
"random_number": "1234",
},
]
}
},
"example2": {
"summary": "登錄傳統發票",
"value": {
"tag": "invoice_trad",
"user": {
"name": "小明",
"email": "test@example.com",
"phone": "0912345678",
},
"invoice": [
{
"invDate": "20230705",
"invNum": "AB12345678",
"mediaId": "64c07d72ee44f30fa6ac7e7a",
},
{
"invDate": "20230706",
"invNum": "AB12345679",
"mediaId": "64c07d72ee44f30fa6ac7e7a",
},
]
}
},
"example3": {
"summary": "登錄個人載具",
"value": {
"tag": "carrier",
"carrier": {
"userId": "64b8d5ece95b7b72e4b249f5",
"name": "小明",
"email": "test@example.com",
"card_no": "/ABC-123",
"card_encrypt": "123456",
},
}
},
}
有了剛剛設計好的 Schema,接著將 examples 傳入到路由
@router.post("", summary="儲存資料")
async def save_invoice(request: Request, save_data: SaveData = Body(..., examples=SaveData.Config.examples)):
# 這邊可以自行加入檢查
data = await perform_save_data(save_data)
return success_response(message="儲存資料成功", data=data)