DZone
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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Adding Graph Retrieval to a RAG Pipeline With Python
  • 3D Air Quality Maps With Neo4j, Python, and R
  • DuckDB for Python Developers
  • Building a Simple MCP Server and Client: An In-Memory Database

Trending

  • AI Coding Agent Guardrails: Finding Gaps in Tool Permissions
  • Nobody Designs an RBAC Mess; Everyone Ends Up With One
  • Beyond @Transactional: Solving the Dual-Write Problem in Distributed Microservices
  • Going All In On the JVM 25 Virtual Threads

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. 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.

By 
Saurabh Dashora
DZone Core CORE ·
Mar. 05, 22 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
7.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

Related

  • Adding Graph Retrieval to a RAG Pipeline With Python
  • 3D Air Quality Maps With Neo4j, Python, and R
  • DuckDB for Python Developers
  • Building a Simple MCP Server and Client: An In-Memory Database

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook