Topics in this subject
FastAPI 3 min read Updated 11 Aug 2026

Path and Query Parameters

Routing, dynamic URLs, optional query strings, and parameter validation.

🧑‍🏫 Sabse pehle — simple mein samjho#

URLs ke zariye server ko data bhejne ke do tareeqe hote hain. Pehla hai Path Parameters (jaise /users/123), jo URL ka hissa hote hain aur specific item dhoondhne ke kaam aate hain. Dusra hai Query Parameters (jaise /users?sort=asc&limit=10), jo URL ke end mein ? ke baad aate hain. Ye list ko filter ya paginate karne ke kaam aate hain. FastAPI in dono ko recognize karna ekdum easy bana deta hai, bas function ke arguments mein naam declare kar do!

1. Path Parameters#

You declare path parameters using curly braces {} in the route decorator, and then pass them as arguments to the path operation function.

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    # Because we typed it as `int`, FastAPI will automatically convert the string from the URL into a Python integer!
    return {"item_id": item_id}

If a user visits /items/foo, FastAPI will automatically return a clear HTTP 422 error because "foo" cannot be converted to an integer.

Order Matters!#

If you have a fixed path (like /users/me) and a dynamic path (like /users/{user_id}), you MUST put the fixed path first. Otherwise, FastAPI will evaluate /users/me as passing the string "me" to the {user_id} parameter.

@app.get("/users/me")
async def read_current_user():
    return {"user_id": "the current user"}

@app.get("/users/{user_id}")
async def read_user(user_id: str):
    return {"user_id": user_id}

2. Query Parameters#

When you declare function parameters that are not part of the URL path, FastAPI automatically interprets them as "query" parameters.

# The URL would look like: /items/?skip=0&limit=10
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
    return {"skip_value": skip, "limit_value": limit}

Making Query Parameters Optional#

To make a query parameter optional, set its default value to None and use Python's str | None typing (or Optional[str] in older Python versions).

# URL could be: /search/?q=fastapi  OR just /search/
@app.get("/search/")
async def search_engine(q: str | None = None):
    if q:
        return {"results": f"Searching for {q}"}
    return {"results": "No search query provided"}

3. String Validations (The Path and Query functions)#

You can add extra validations (like min length, max length, or regex patterns) to your parameters by importing Path and Query from FastAPI.

from fastapi import FastAPI, Query, Path

app = FastAPI()

@app.get("/users/{user_id}")
async def read_user(
    # Ensure user_id is greater than 0
    user_id: int = Path(title="The ID of the user", gt=0),
    
    # Ensure the query string 'q' has at least 3 characters and max 50
    q: str | None = Query(default=None, min_length=3, max_length=50)
):
    return {"user_id": user_id, "query": q}