Script Valley
FastAPI: Build Production Python APIs
FastAPI FoundationsLesson 1.2

How to define path parameters and query parameters in FastAPI

path parameters, query parameters, optional parameters, default values, type coercion, parameter validation, URL structure

Path and Query Parameters

FastAPI reads parameters directly from function signatures. The framework matches them to path segments or query strings automatically based on whether the name appears in the route path.

Path parameters

Wrap the name in curly braces in the route string and add it as a typed function argument:

from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}")
def get_user(user_id: int):
    return {"user_id": user_id}

FastAPI coerces the string from the URL to int. If the caller passes /users/abc, the framework returns a 422 automatically — no manual validation needed.

Query parameters

Any function argument not in the path becomes a query parameter:

@app.get("/items/")
def list_items(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

Call /items/?skip=20&limit=5. Default values make parameters optional. Without a default, the parameter is required and FastAPI returns 422 if the caller omits it.

Optional parameters with None

from typing import Optional

@app.get("/search/")
def search(q: Optional[str] = None):
    if q:
        return {"query": q}
    return {"query": "all"}

Use Optional[str] = None when the parameter may be absent entirely. FastAPI treats None as the absence of the parameter, not an empty string.

Up next

How to validate request bodies with Pydantic models in FastAPI

Sign in to track progress