API Parameters in FastAPI — The Ultimate Guide

Ayesha MughalAyesha Mughal
3 min read

When building APIs in FastAPI, handling user input correctly is critical. Whether you’re accepting a product ID from the URL or filters from a query string, FastAPI makes it clean and intuitive.

In this guide, you’ll learn how to:

  • ✅ Use Path Parameters

  • ✅ Use Query Parameters

  • ✅ Add Validation using Path() and Query()

  • ✅ Combine parameters for powerful endpoints


⚙️ 1. Path Parameters

These are parts of the URL path itself, like /items/42. FastAPI automatically parses and validates them based on your function signature.

from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(
    item_id: int = Path(
        ...,  # required
        title="The ID of the item",
        description="A unique identifier for the item",
        ge=1  # must be >= 1
    )
):
    return {"item_id": item_id}

✅ You can:

  • Add title, description → for API docs

  • Use constraints like ge, le, gt, lt


🧭 2. Query Parameters

These are added after a ? in the URL like:

/items?q=shoes&skip=0&limit=10

They're used for filtering, sorting, pagination, etc.

from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/items/")
async def read_items(
    q: str | None = Query(
        None,
        title="Search query",
        description="Search string for items",
        min_length=3,
        max_length=50
    ),
    skip: int = Query(0, ge=0),
    limit: int = Query(10, le=100)
):
    return {"q": q, "skip": skip, "limit": limit}

✅ You can:

  • Set default values

  • Add min_length, max_length, ge, le for strict validation

  • Use optional (| None) parameters


🔀 3. Combining Path, Query, and Body

You can accept all types of input together in a single endpoint:

from fastapi import FastAPI, Path, Query, Body
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str | None = None
    price: float

app = FastAPI()

@app.put("/items/validated/{item_id}")
async def update_item(
    item_id: int = Path(..., ge=1),
    q: str | None = Query(None, min_length=3),
    item: Item | None = Body(None)
):
    result = {"item_id": item_id}
    if q:
        result["q"] = q
    if item:
        result["item"] = item.model_dump()
    return result

🚀 How To Run It

  1. Create a FastAPI project:
uv init fastdca_p1
cd fastdca_p1
uv venv
source .venv/bin/activate
uv add "fastapi[standard]"
  1. Save code in main.py

  2. Run:

fastapi dev main.py
  1. Test it at: http://localhost:8000/docs

✅ Quick Recap

FeatureUseValidation Available
Path()For URL path variablesge, le, title, etc.
Query()For optional query stringsmin_length, max_length, le, etc.
Body()For structured JSON inputWith Pydantic models

🧠 Best Practices

  • Always validate input: never trust user data blindly

  • Use type hints and constraints to auto-document and auto-validate

  • Keep your endpoints clean, clear, and well-structured

  • Use Swagger UI (/docs) to test everything easily


Up Next: Dependency Injection in FastAPI — make your code modular, reusable, and even more elegant.

Happy coding, lovely minds 💖

Written with 💻, ☕, and too much love by Ayesha Mughal a.k.a MughalSyntax

0
Subscribe to my newsletter

Read articles from Ayesha Mughal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ayesha Mughal
Ayesha Mughal

💻 CS Student | Python & Web Dev Enthusiast 🚀 Exploring Agentic AI | CS50x Certified ✨ Crafting logic with elegance