DZone
Microservices Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Microservices Zone > How To Perform FastAPI Path Parameter Validation Using Path Function

How To Perform FastAPI Path Parameter Validation Using Path Function

Learn how to validate path parameters in FastAPI using Path Function.

Saurabh Dashora user avatar by
Saurabh Dashora
CORE ·
Mar. 05, 22 · Microservices Zone · Tutorial
Like (8)
Save
Tweet
6.00K Views

Join the DZone community and get the full member experience.

Join For Free

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:

Python
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:

Python
@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.

JSON
 
{
    "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:

Python
@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.

Python
@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:

Python
@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:

Python
@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.

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

Database Python (language)

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Top ALM Tools and Solutions Providers
  • Delegating JWT Validation for Greater Flexibility
  • Anypoint CLI Commands in MuleSoft
  • No Code Expectations vs Reality

Comments

Microservices Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo