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
7
as 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=shoes
is a search term -
limit=10
restricts 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
Enum
for 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.