Home FastAPI (4) Validation Conditions(中文)
Post
Cancel

FastAPI (4) Validation Conditions(中文)

為什麼需要 Validation Conditions

之前提到 Type Hint 可以幫助 我們 call API 時,防止參數 type 錯誤,一旦 type 錯誤 API 會回復哪個參數 type 錯誤。 這樣不是就很好了,幹嘛還要 Validation Conditions ? 有寫過 Unit Test 的人都知道,有時候 Function 出錯是因為傳入 type 正確但不合理的 value ex: 某個人身高 0.1 公分, 某個人的體重 10000 公斤…etc.

引入 fastapi 下 Path 處理 Validation Conditions

以下介紹最常見的,字串長度以及數字大小限制

1
2
3
4
5
6
7
import uvicorn
from fastapi import FastAPI, Path
app = FastAPI()

@app.get("/test2/{name}")
async def test2_1(name:str=Path(..., min_length=3, max_length=10)):
    return {"name":name}

上述例子要求傳入 {name} 參數 type 為 str, 且長度介於 3 ~ 10 之間

http://localhost:8000/test2/abc

Desktop View

http://localhost:8000/test2/ab

Desktop View

http://localhost:8000/test2/abcdefghijk

Desktop View

1
2
3
4
5
6
7
8
import uvicorn
from fastapi import FastAPI, Path
app = FastAPI()

@app.get("/test2/{weight}")
async def test2_1(weight:int=Path(..., ge=40, le=120)):
    return {"weight":weight}

http://localhost:8000/test2/45

Desktop View

http://localhost:8000/test2/20

Desktop View

http://localhost:8000/test2/130

Desktop View

拍謝,胖虎你被排除了(128 公斤)

Desktop View image from: https://www.basketball-reference.com/players/w/willizi01.html

總結

Validation Conditions 可以在參數型別正確的情況下,限制輸入的範圍(避免測試人員惡搞),避免不合理的輸入值,造成非預期的錯誤。

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍