Skip to content

Path and Query ParametersΒΆ


🎯 Goal¢

Understand how to use dynamic values in your API routes via:

  • Path parameters: embedded in the URL path
  • Query parameters: passed after a ? in the URL

FastAPI uses Python type hints to automatically validate these inputs and generate documentation.


πŸ”— Path ParametersΒΆ

Path parameters are part of the URL itself and are used to identify specific resources.

πŸ§ͺ Example: Greeting by NameΒΆ

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello/{name}")
def say_hello(name: str):
    return {"message": f"Hello, {name}!"}
  • {name} is a placeholder in the URL.
  • FastAPI extracts it and passes it to the function as a str.

🧭 Try:

  • /hello/Alice β†’ {"message": "Hello, Alice!"}
  • /hello/Bob β†’ {"message": "Hello, Bob!"}

πŸ”’ Type Conversion and ValidationΒΆ

You can specify types like int, float, or bool. FastAPI will:

  • Convert the value automatically
  • Return a 422 error if the type is invalid
@app.get("/square/{number}")
def square(number: int):
    return {"result": number ** 2}

🧭 Try:

  • /square/5 β†’ {"result": 25}
  • /square/five β†’ ❌ 422 error: invalid integer

❓ Query ParametersΒΆ

Query parameters are passed in the URL after a ?, like /search?term=fastapi.

πŸ§ͺ Example: Search EndpointΒΆ

@app.get("/search")
def search(term: str, limit: int = 10):
    return {"term": term, "limit": limit}
  • term is required
  • limit is optional (default = 10)

🧭 Try:

  • /search?term=fastapi&limit=5 β†’ {"term": "fastapi", "limit": 5}
  • /search?term=python β†’ {"term": "python", "limit": 10}

🧠 Optional Parameters¢

You can make parameters optional by giving them default values:

@app.get("/filter")
def filter_items(category: str = "all", active: bool = True):
    return {"category": category, "active": active}

🧭 Try:

  • /filter β†’ {"category": "all", "active": true}
  • /filter?category=books&active=false β†’ {"category": "books", "active": false}

FastAPI automatically converts "false" to False, "true" to True.


πŸ§ͺ Combined Example: Path + QueryΒΆ

@app.get("/users/{user_id}")
def get_user(user_id: int, details: bool = False):
    return {"user_id": user_id, "details": details}

🧭 Try:

  • /users/42 β†’ {"user_id": 42, "details": false}
  • /users/42?details=true β†’ {"user_id": 42, "details": true}

🧠 Practice Challenge¢

Try building these endpoints:

  • /multiply/{x}/{y} β†’ returns product of two integers
  • /weather?city=Osaka&units=metric β†’ returns mock weather data
  • /profile/{username}?show_email=true β†’ returns user profile with optional email