Home FastAPI (4) Validation Conditions(English)
Post
Cancel

FastAPI (4) Validation Conditions(English)

Why We Need Validation Conditions

As mentioned before, Type Hint can help prevent parameter type errors when calling an API. If there is a type error, the API will indicate which parameter has the incorrect type. This is quite useful, so why do we still need validation conditions?

Anyone who has written unit tests knows that sometimes a function fails because of correct type but unreasonable value being passed in. For example, a person’s height being 0.1 cm, or a person’s weight being 10,000 kg…etc.

Introducing Validation Conditions with FastAPI’s Path Handling

Below is an introduction to the most common conditions, such as string length and number size limits.

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}

The example requires the {name} parameter to be of type str and to have a length between 3 and 10 characters.

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

Sorry, Zion Williamson, you are excluded (128 kg).

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

Summary

Validation conditions can limit the range of input values when the parameter type is correct (to avoid testers messing around) and prevent unreasonable input values, thus avoiding unexpected errors.

☝ツ☝

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

👈 ツ 👍