On this page

Path Parameters and Query Parameters in FastAPI

Published on August 9, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A FastAPI route can accept dynamic input two different ways: as a path parameter, embedded directly in the URL like /hello/Alice, or as a query parameter, appended after a ? like /search?term=fastapi. Both are declared the same way — as a type-hinted argument on the path operation function — and both get the same automatic validation, but which one a given argument becomes isn't something declared explicitly. FastAPI decides based on one simple rule: if a function argument's name appears inside {curly braces} in the route's path string, it's a path parameter; otherwise, it's treated as a query parameter automatically.


Path Parameters​

Path parameters identify a specific resource as part of the URL itself, rather than as extra information attached after it.


from fastapi import FastAPI



app = FastAPI()



@app.get("/hello/{name}")

def say_hello(name: str):

    return {"message": f"Hello, {name}!"}

{name} in the decorator's path string is a placeholder. FastAPI matches that segment of the incoming URL, extracts it, and passes it into say_hello as the name argument — typed as str here, so /hello/Alice returns {"message": "Hello, Alice!"} and /hello/Bob returns {"message": "Hello, Bob!"}, with the captured text passed through unchanged.

Type conversion and validation on path parameters​

Declaring a narrower type than str — int, float, or bool — makes FastAPI actively convert and validate the captured value rather than just accepting whatever text was in the URL:


@app.get("/square/{number}")

def square(number: int):

    return {"result": number ** 2}

/square/5 converts the captured text "5" into the integer 5 before square runs, returning {"result": 25}. /square/five fails that conversion, since "five" can't become an integer, and FastAPI responds with a 422 Unprocessable Entity error describing exactly which parameter failed and why — the function body never executes at all in that case.


Query Parameters​

Any function argument that isn't captured inside the path's {} placeholders becomes a query parameter instead, read from the part of the URL after ?:


@app.get("/search")

def search(term: str, limit: int = 10):

    return {"term": term, "limit": limit}

Neither term nor limit appears in "/search" itself, which is exactly what makes FastAPI treat both as query parameters rather than path parameters. term has no default value, so it's required — a request to /search with no term at all returns a 422 error. limit has a default of 10, which makes it optional: /search?term=fastapi&limit=5 returns {"term": "fastapi", "limit": 5}, while /search?term=python (omitting limit entirely) returns {"term": "python", "limit": 10}, falling back to the default.


Optional Parameters and Defaults​

Giving any parameter a default value is what makes it optional — the same mechanism limit used above applies just as well to non-numeric types:


@app.get("/filter")

def filter_items(category: str = "all", active: bool = True):

    return {"category": category, "active": active}

/filter with no query string at all returns {"category": "all", "active": true}, falling back to both defaults. /filter?category=books&active=false returns {"category": "books", "active": false}.

The bool conversion happening on active is worth being precise about, since it's easy to assume only the literal words "true" and "false" work. FastAPI's underlying validation (through Pydantic) accepts a specific, fixed set of case-insensitive strings for a bool field: 1, on, t, true, y, and yes all convert to True; 0, off, f, false, n, and no all convert to False. Anything outside that set — active=maybe, for instance — doesn't silently fall back to False; it fails validation and returns a 422 error the same way an invalid int does, since the framework has no way to know what a value outside that recognized set was actually meant to represent.


Combining Path and Query Parameters​

Path and query parameters aren't mutually exclusive — a single route commonly uses both at once, and FastAPI tells them apart by the same rule already covered: whether the argument's name shows up inside the path string's {} or not.


@app.get("/users/{user_id}")

def get_user(user_id: int, details: bool = False):

    return {"user_id": user_id, "details": details}

user_id is captured from the path (it appears inside {user_id}), while details is a query parameter with a default, since it appears nowhere in "/users/{user_id}". /users/42 returns {"user_id": 42, "details": false}, and /users/42?details=true returns {"user_id": 42, "details": true} — one value embedded in the URL's structure, the other appended after it.


Practice: Building Three More Endpoints​

Applying the same rules to three additional routes:


@app.get("/multiply/{x}/{y}")

def multiply(x: int, y: int):

    return {"product": x * y}



@app.get("/weather")

def weather(city: str, units: str = "metric"):

    mock_temperatures = {"metric": 21, "imperial": 70}

    return {"city": city, "units": units, "temperature": mock_temperatures[units]}



@app.get("/profile/{username}")

def profile(username: str, show_email: bool = False):

    data = {"username": username}

    if show_email:

        data["email"] = f"{username}@example.com"

    return data

/multiply/{x}/{y} shows that a route can declare more than one path parameter in the same string — /multiply/3/4 returns {"product": 12}, with both x and y captured and converted to int independently. /weather uses only query parameters, since neither city nor units appears in "/weather" itself, with units optional and defaulting to "metric". /profile/{username} combines a required path parameter with an optional query parameter, and unlike the earlier examples, the response itself changes shape based on that optional value — the email field is only added to the returned dictionary when show_email evaluates to True, rather than being present but empty otherwise.

Key Takeaways​

Path and query parameters both start from the same place — a type-hinted argument on a path operation function — and the only thing separating them is whether that argument's name appears inside the route's {} placeholders. A default value is what turns any parameter optional, whether it's a query parameter like limit or a broader type like bool, and every type hint on either kind of parameter is enforced the same way: converted where possible, rejected with a 422 error where not. The bool type in particular accepts a specific, fixed set of string values rather than only the literal words true and false, and falls back to a validation error — not a silent default — for anything outside that set.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Creating Multiple Endpoints and HTTP Methods

Next

Type Validation and Automatic Documentation