0
0
FastAPIframework~30 mins

Path parameter types and validation in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Path Parameter Types and Validation with FastAPI
📖 Scenario: You are building a simple web API for a bookstore. The API needs to get book details by their ID and filter books by their rating.
🎯 Goal: Create a FastAPI app that uses path parameters with specific types and validation to ensure correct input from users.
📋 What You'll Learn
Create a FastAPI app instance named app
Define a path parameter book_id as an integer in the route /books/{book_id}
Add validation to book_id so it must be greater than 0
Define a path parameter rating as a float in the route /books/rating/{rating}
Add validation to rating so it must be between 0.0 and 5.0 inclusive
Return simple JSON responses confirming the received parameters
💡 Why This Matters
🌍 Real World
APIs often need to accept user input in URLs. Validating these inputs ensures the API works correctly and securely.
💼 Career
Understanding path parameter types and validation is essential for backend developers building reliable web services with FastAPI.
Progress0 / 4 steps
1
Create FastAPI app and integer path parameter
Import FastAPI from fastapi and create an app instance called app. Then define a GET route /books/{book_id} with a path parameter book_id of type int. The function should return a dictionary with the key book_id and its value.
FastAPI
Need a hint?

Use app = FastAPI() to create the app. Define a function with book_id: int as parameter and decorate it with @app.get("/books/{book_id}").

2
Add validation for book_id to be greater than 0
Import Path from fastapi. Update the book_id parameter to use Path(..., gt=0) to enforce that book_id must be greater than 0.
FastAPI
Need a hint?

Use Path(..., gt=0) to require book_id to be greater than zero.

3
Add float path parameter with range validation
Define a new GET route /books/rating/{rating} with a path parameter rating of type float. Use Path(..., ge=0.0, le=5.0) to validate that rating is between 0.0 and 5.0 inclusive. The function should return a dictionary with the key rating and its value.
FastAPI
Need a hint?

Define a new async function with rating: float = Path(..., ge=0.0, le=5.0) and decorate it with @app.get("/books/rating/{rating}").

4
Complete FastAPI app with both routes and validation
Ensure the FastAPI app has both routes: /books/{book_id} with book_id as an integer path parameter validated to be greater than 0, and /books/rating/{rating} with rating as a float path parameter validated between 0.0 and 5.0 inclusive. Both routes should return JSON with the received parameter.
FastAPI
Need a hint?

Make sure both routes and their validations are present in the app code.