English 中文(简体)
FastAPI - Parameter Validation
  • 时间:2024-12-22

FastAPI - Parameter Vapdation


Previous Page Next Page  

It is possible to apply vapdation conditions on path parameters as well as query parameters of the URL. In order to apply the vapdation 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": {
            "pmit_value": 10
         }
      }
   ]
}

The OpenAPI docs also shows the vapdations appped −

FastAPI Parameter Vapdation

Vapdation rules can be appped 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 vapdations.


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, vapdation rules are appped 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 vapdation failure −


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

The swagger UI documentation also identifies the constraints.

FastAPI Parameter Vapdation

The query parameters can also have the vapdation rules appped 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 vapdation 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 vapdation conditions appped. It is reflected in the OpenAPI documentation as follows −

FastAPI Parameter Vapdation

While the cpent 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 pbrary for this purpose.

Advertisements