Welcome to Day 2 of the #FastAPIDaily series!
Today, weβre diving deep into the world of Path Parameters and Query Parameters β the foundation of any dynamic and flexible RESTful API.
π§± Path Parameters β Dynamic Values in the URL
π What are Path Parameters?
Path parameters are parts of the URL that capture dynamic values. These values are embedded directly into the path of the endpoint.
π Example:
/users/123
Here, 123 is a dynamic user ID β a path parameter.
π§° Why Use Path Parameters?
- To identify a specific resource (e.g., product, user, order)
- When the value is required for the endpoint to make sense
- For RESTful, clean, and readable URLs
π§ͺ How to Use Path Parameters in FastAPI
Create a file with name as path.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
π Command to Run
uvicorn path:app --host 0.0.0.0 --port 9000 --reload
β
Expected Output
Once the server is running, open your browser and visit:
http://127.0.0.1:9000/items/7 -->

π When a user visits /items/7, FastAPI:
- Captures
7as the value ofitem_id - Validates it as an
int - Returns it in a JSON response
π Real-Life Examples of Path Parameters
| Use Case | Endpoint Example |
|---|---|
| Get user profile | /users/{user_id} |
| View a blog post | /posts/{post_id} |
| Fetch product details | /products/{product_id} |
| Download a file by name | /files/{filename} |
π― Type Validation with Path Parameters
FastAPI automatically validates path parameter types based on Python type hints. This allows you to catch errors before they reach your logic.
@app.get("/score/{value}")
def get_score(value: float):
return {"score": value}
π₯ Test URLs
- β
/score/99.5β{ "score": 99.5 }
- β
/score/highβ422 Unprocessable Entity(invalid float)
π Enum in Path Parameter (Restrict Values)
Use Enum to restrict path values to a fixed set of allowed values.
from enum import Enum
from fastapi import FastAPI
class Category(str, Enum):
books = "books"
electronics = "electronics"
clothing = "clothing"
app = FastAPI()
@app.get("/category/{cat}")
def get_category(cat: Category):
return {"category": cat}
π― Test
- β
/category/booksβ{ "category": "books" }
- β
/category/groceryβ422 Unprocessable Entity
π§ͺ Multiple Path Parameters
You can pass multiple parameters in a single path route.
@app.get("/school/{school_id}/student/{student_id}")
def get_student(school_id: int, student_id: int):
return {
"school": school_id,
"student": student_id
}
β Common Mistakes to Avoid
| Mistake | Why it Fails |
|---|---|
| Sending body in GET request | β Violates HTTP standards |
| Wrong type (e.g., string in int param) | β FastAPI returns 422 validation error |
| Optional path parameter | β Not supported directly in FastAPI |
π Query Parameters β Flexible & Optional Inputs in FastAPI
π What are Query Parameters?
Query parameters are optional values added after a ? in a URL.
They allow clients to send filters, sorting options, pagination, and more without changing the structure of the endpoint.
π§ͺ Example:
/search?q=shoes&limit=10
Here:
-
q=shoesis a search term -
limit=10restricts results to 10 items
π§° Why Use Query Parameters?
- β Add optional input like filters and sorting
- β Control pagination and result limits
- β Enable advanced search using multiple fields
- β Maintain a clean and RESTful endpoint design
π§ͺ How to Use Query Parameters in FastAPI
Create a file with name as queryparam.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/search")
def search_items(q: str, limit: int = 10):
return {"query": q, "limit": limit}
π Command to Run
uvicorn queryparam:app --host 0.0.0.0 --port 9001 --reload
β
Expected Output
Once the server is running, open your browser and visit:
http://127.0.0.1:9001/search?q=laptop&limit=5 -->
If limit is not provided, it defaults to 10
π Real-Life Examples of Query Parameters
| Use Case | Endpoint Example |
|---|---|
| Filter products by category | /products?category=electronics |
| Paginate user data | /users?page=2&limit=25 |
| Search blog posts | /posts?keyword=fastapi&author=utkarsh |
| Sort item list | /items?sort=price&order=asc |
π₯ Advanced Query Parameter Examples
π Optional Query Parameters
You can make parameters optional using Optional from typing.
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/products")
def get_products(brand: Optional[str] = None):
if brand:
return {"message": f"Showing products for {brand}"}
return {"message": "Showing all products"}
π§ͺ Test:
β /products
β /products?brand=Nike
π Real-World Summary
Both path and query parameters are essential for building flexible, scalable APIs in FastAPI.
Use Path Parameters to get specific items:
β€/orders/500β Get order with ID 500Use Query Parameters to filter or adjust the response:
β€/orders?limit=10&status=shippedβ Get last 10 shipped orders
β Summary β What You Learned Today
On Day 2 of the #FastAPIDaily journey, you unlocked the real power behind building dynamic and user-focused APIs using:
πΉ Path Parameters
- Used to identify specific resources like a user, product, or order
- Always required and part of the URL structure
- Automatically validated by FastAPI using Pythonβs type hints
- Can be restricted using
Enumfor safe, fixed-value routes
π Example: /users/101 β fetch details for user with ID 101
πΉ Query Parameters
- Used to filter, sort, or paginate results
- Flexible and optional β perfect for building responsive and interactive APIs
- Great for search filters, result limits, advanced search features, and more
- Defaults can be set and parameters can be marked optional using
Optional
π Example: /products?brand=Nike&limit=5 β show 5 Nike products
π§ Real-Life Scenarios
| π‘ Scenario | β Path Parameter Example | π Query Parameter Example |
|---|---|---|
| Get a specific user | /users/42 |
β |
| Filter products by brand | β | /products?brand=Adidas |
| Get order details | /orders/8912 |
β |
| Advanced blog post search | β | /posts?keyword=fastapi&author=utkarsh |
| Paginate users | β | /users?page=3&limit=25 |
| Filter logs by type/date | β | /logs?level=error&from=2024-06-01 |
| View product category (restricted) |
/category/clothing (with Enum) |
β |
π― Final Thoughts
By mastering Path and Query Parameters, youβve taken a major step in building scalable, maintainable, and REST-compliant APIs using FastAPI.
π§ Quick Tip:
If a value is essential to identify a resource β use a Path Parameter.
If a value is meant to filter or modify the result β use a Query Parameter.
Keep practicing these principles and you'll be designing clean, flexible APIs in no time! πͺ
π Credits
Huge thanks to the FastAPI Official Documentation by SebastiΓ‘n RamΓrez (@tiangolo) β the best place to learn and explore everything about FastAPI.
π¨βπ» About Me
Hey there! Iβm Utkarsh Rastogi, an AWS Community Builder and passionate cloud-native enthusiast who loves building scalable backend systems and sharing knowledge with the community.
π Connect with me: Utkarsh Rastogi
π¬ Share Your Thoughts β I'd Love Your Feedback!
If you enjoyed today's post or learned something new, I'd truly appreciate it if you leave a comment or share your thoughts π
Your feedback, questions, or even a quick βπ₯ Loved this!β keeps me motivated to continue this journey and share more in the upcoming #FastAPIDaily posts.
β
What did you find most helpful?
β
Anything you'd like explained in the next part?
β
Suggestions for improvement? Iβm all ears! π
Letβs grow and learn together β one FastAPI day at a time π








Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.