How To Perform FastAPI Path Parameter Validation Using Path Function

In this post, we will learn how to perform FastAPI Path Parameter Validation. We will specifically also learn how to use the Path() function to handle the validations in a declarative approach.

Using the Path function is quite similar to using the Query function. In other words, we can declare validations as well as meta-data using the Path function. Please refer to the post on FastAPI Query Parameter validation to know more about the same.

FastAPI Path Parameter Metadata Example

We can declare a request handler with path parameter as below:

from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/books/{book_id}")
def read_books(book_id: int = Path(..., title="The ID of the Book")):
    output = {"book_id": book_id}
    return output

Here, book_id is a path parameter. In the read_books function, we specify book_id to be of type int. Also, we use the Path function to specify the meta-data title.

The same title information will appear in the interactive docs.

A path parameter is always required. Otherwise, the path becomes invalid. Therefore, we should use … to mark it as required.
However, even if we declare it with None or another default value instead of …, it would still be required.

Numeric Validations: Greater Than or Equal

We can use the Path function to declare numeric validations.

See the below example:

@app.get("/books/{book_id}")
def read_books(book_id: int = Path(..., title="The ID of the Book", ge=1)):
    output = {"book_id": book_id}
    return output

Here, we use ge=1 to specify that our path parameter value should be greater than or equal to 1. In case of violation, we get the below error response.

{
    "detail": [{
        "loc": ["path", "book_id"],
        "msg": "ensure this value is greater than or equal to 1",
        "type": "value_error.number.not_ge",
        "ctx": {
            "limit_value": 1
        }
    }]
}

Numeric Validations: Greater Than and Less Than

We can also place multiple conditions as below:

@app.get("/books/{book_id}")
def read_books(book_id: int = Path(..., title="The ID of the Book", gt=0, lt=100)):
    output = {"book_id": book_id}
    return output

Here, we use both gt and lt to specify the range of values. The value of book_id should be greater than 0 but less than 100.

Float Validations

The validations also work for float values.

@app.get("/books/{book_price}")
def read_books(book_price: float = Path(..., title="The Price of the Book", gt=1.5, lt=10.5)):
    output = {"book_price": book_price}
    return output

As you can see, we declare book_price to be a float value. Then, we use gt and lt to specify the range of price.

Parameter Ordering

Sometimes, we need to declare a query parameter along with a path parameter. Consider that the query parameter is always required and that is the only validation for the parameter. In such a case, we don’t need to use the Query function.

However, we would still need Path function for the path parameter. In such a case, Python will complain with the error Non default argument follows default argument if we put a value with a default before the value without default.

To avoid this, we can reorder the arguments to have the query parameter before the path parameter. FastAPI will be able to figure out the appropriate argument based on name, types and default declarations.

See the below example:

@app.get("/books/{book_price}")
def read_books(test: str, book_price: float = Path(..., title="The Price of the Book", gt=1.5, lt=10.5)):
    output = {"book_price": book_price}
    return output

Here, we place the query parameter test as the first argument.

Another way to get around this issue is to use * as first argument. See the below example:

@app.get("/books/{book_price}")
def read_books(*, book_price: float = Path(..., title="The Price of the Book", gt=1.5, lt=10.5), test: str):
    output = {"book_price": book_price}
    return output

By using *, Python will know that all following parameters should be called as keyword arguments (also known as kwargs).

Conclusion

With this, we have successfully learned how to perform FastAPI Path Parameter validation using Path function.

If you have any comments or queries about the same, please write in the comments section below.

.

Leave a Comment