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 browser’s 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

Let us modify the above operation decorator to include age as a path parameter and apply the validations.

from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/hello/{name}/{age}")
async def hello(*, name: str=Path(...,min_length=3 , max_length=10), age: int = Path(..., ge=1, le=100)):
   return {"name": name, "age":age}

In this case, validation rules are applied for both the parameters name and age. If the URL entered is http://localhost:8000/hello/hi/110, then the JSON response shows following explanations for validation failure −

{
   "detail": [
      {
         "loc": [
            "path",
            "name"
         ],
         "msg": "ensure this value has at least 3 characters",
         "type": "value_error.any_str.min_length",
         "ctx": {
            "limit_value": 3
         }
      },
      {
         "loc": [
            "path",
            "age"
         ],
         "msg": "ensure this value is less than or equal to 100",
         "type": "value_error.number.not_le",
         "ctx": {
            "limit_value": 100
         }
      }
   ]
}

The swagger UI documentation also identifies the constraints.

FastAPI Parameter Validation

The query parameters can also have the validation rules applied to them. You have to specify them as the part of arguments of Query class constructor.

Let us add a query parameter called percent in the above function and apply the validation rules as ge=0 (i.e., greater then equal to 0) and lt=100 (less than or equal to 100)

from fastapi import FastAPI, Path, Query
@app.get("/hello/{name}/{age}")
async def hello(*, name: str=Path(...,min_length=3 ,
max_length=10), \
      age: int = Path(..., ge=1, le=100), \
      percent:float=Query(..., ge=0, le=100)):
   return {"name": name, "age":age}

If the URL entered is http://localhost:8000/hello/Ravi/20?percent=79, then the browser displays following JSON response −

{"name":"Ravi","age":20}

FastAPI correctly identifies percent as a query parameter with validation conditions applied. It is reflected in the OpenAPI documentation as follows −

FastAPI Parameter Validation

While the client can send the path and query parameters to the API server using GET method, we need to apply POST method to send some binary data as a part of the HTTP request. This binary data may be in the form of an object of any Python class. It forms the request body. FastAPI uses Pydantic library for this purpose.

Advertisements