API Development

Parameter Validation

API Development / Parameter Validation

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 −

FastAPI Parameter Validation

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

Technology
API Development
want to connect with us ?
Contact Us