DEV Community

Cover image for Day 2: Path Parameters & Query Parameters in FastAPI
Utkarsh Rastogi
Utkarsh Rastogi

Posted on β€’ Edited on

Day 2: Path Parameters & Query Parameters in FastAPI

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
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

πŸš€ 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 -->
Path

πŸ” When a user visits /items/7, FastAPI:

  • Captures 7 as the value of item_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}
Enter fullscreen mode Exit fullscreen mode

πŸ”₯ Test URLs

  • βœ… /score/99.5 β†’ { "score": 99.5 }

Score

  • ❌ /score/high β†’ 422 Unprocessable Entity (invalid float)

ScoreHigh


πŸ“˜ 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}
Enter fullscreen mode Exit fullscreen mode

🎯 Test

  • βœ… /category/books β†’ { "category": "books" }

Books

  • ❌ /category/grocery β†’ 422 Unprocessable Entity

Grocery


πŸ§ͺ 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
    }
Enter fullscreen mode Exit fullscreen mode

School


❌ 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}

Enter fullscreen mode Exit fullscreen mode

πŸš€ 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 -->

QueryParam

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"}
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Test:

βœ… /products

Products

βœ… /products?brand=Nike

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 500

  • Use 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.