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.

1 – 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.

fastapi path parameter validation
beenhere

INFO

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.

2 – Numeric Validations : Greater than or equal

We can use the Path function to declare numeric validations.

See 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
		}
	}]
}

3 – 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.

4 – 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.

5 – 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 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 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 learnt how to perform FastAPI Path Parameter validation using Path function.

Want to learn how to handle request body in FastAPI? Check out this post on FastAPI Request Body Using Pydantic.

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

Categories: BlogFastAPI

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *