Parameter Validation
FastAPI - Parameter Validation
It is possible to apply validation conditions on path parameters as well as query parameters of the URL. In order to apply the validation conditions on a path parameter, you need to import the Path class. In addition to the default value of the parameter, you can specify the maximum and minimum length in the case of a string parameter.
from fastapi import FastAPI, Path app = FastAPI() @app.get("/hello/{name}") async def hello(name:str=Path(...,min_length=3, max_length=10)): Β return {"name": name}
If the browsers URL contains the parameter with a length less than 3 or more than 10, as in (http://localhost:8000/hello/Tutorialspoint), there will be an appropriate error message such as β
{ Β "detail": [ Β Β Β { Β Β Β Β "loc": [ Β Β Β Β Β Β "path", Β Β Β Β Β Β "name" Β Β Β Β ], Β Β Β Β "msg": "ensure this value has at most 10 characters", Β Β Β Β "type": "value_error.any_str.max_length", Β Β Β Β "ctx": { Β Β Β Β Β Β "limit_value": 10 Β Β Β Β } Β Β Β } Β ] }
The OpenAPI docs also shows the validations applied β

Validation rules can be applied on numeric parameters too, using the operators as given below β
gt β greater than
ge β greater than or equal
lt β less than
le β less than or equal