Python Academy · Lesson

Path Parameters, Query Params, and Request Bodies

Define typed parameters and request body schemas with Pydantic.

Lesson 2 of 413 steps

Path Parameters, Query Params, and Request Bodies is a free Python Academy lesson on CoddyKit. This is lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, and your progress syncs across the web and the CoddyKit app. The Python Academy course includes 4 lessons in total.

Path Parameter Validation

Add validators to path parameters using Path(): set ge, le, gt, lt constraints.

from fastapi import FastAPI, Path
app = FastAPI()

@app.get("/items/{item_id}")
def get_item(item_id: int = Path(ge=1, le=1000)):
    return {"item_id": item_id}

# GET /items/0  → 422 (must be >= 1)

Query Parameter Validation

Use Query() to add validation, default values, aliases, and descriptions to query parameters.

from fastapi import FastAPI, Query
app = FastAPI()

@app.get("/search")
def search(
    q: str = Query(min_length=2, max_length=50),
    page: int = Query(default=1, ge=1),
):
    return {"q": q, "page": page}

Optional Query Params

Use | None = None (Python 3.10+) or Optional[str] = None to make a query parameter optional.

from fastapi import FastAPI
app = FastAPI()

@app.get("/users")
def list_users(
    dept: str | None = None,
    active: bool = True
):
    return {"dept": dept, "active": active}

# GET /users → dept=None, active=True
# GET /users?dept=HR&active=false

Multiple Values for One Query Param

Accept a list of values for a single query parameter with list[str] and Query().

from fastapi import FastAPI, Query
from typing import Annotated
app = FastAPI()

@app.get("/filter")
def filter_items(tags: Annotated[list[str], Query()] = []):
    return {"tags": tags}

# GET /filter?tags=python&tags=web

Nested Request Bodies

Pydantic models can be nested. FastAPI handles nested JSON automatically.

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()

class Address(BaseModel):
    street: str
    city: str

class User(BaseModel):
    name: str
    address: Address

@app.post("/users")
def create_user(user: User):
    return user.model_dump()

Field Constraints in Pydantic

Use Field() inside a model to add constraints, defaults, and descriptions to individual fields.

from pydantic import BaseModel, Field

class Product(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    price: float = Field(gt=0)
    quantity: int = Field(ge=0, default=0, description="Items in stock")

Request Body + Path + Query Together

Mix all three parameter types in one endpoint. FastAPI distinguishes them by position: path in URL, simple types as query, models as body.

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()

class ItemUpdate(BaseModel):
    name: str
    price: float

@app.put("/shops/{shop_id}/items/{item_id}")
def update_item(
    shop_id: int,
    item_id: int,
    item: ItemUpdate,
    notify: bool = False,
):
    return {"shop": shop_id, "item": item_id,
            "data": item.model_dump(), "notify": notify}

File Uploads

Use UploadFile and File() to accept file uploads. Access content with await file.read().

from fastapi import FastAPI, UploadFile, File
app = FastAPI()

@app.post("/upload")
async def upload(file: UploadFile = File(...)):
    content = await file.read()
    return {"filename": file.filename, "size": len(content)}

Form Data

Use Form() to accept HTML form data (application/x-www-form-urlencoded or multipart/form-data).

# pip install python-multipart
from fastapi import FastAPI, Form
app = FastAPI()

@app.post("/login")
def login(username: str = Form(...), password: str = Form(...)):
    return {"username": username}

Request Validation Summary

FastAPI validates all parameter types automatically. Invalid inputs return HTTP 422 with a detailed error before your handler is called.

# Auto-validated:
# - Path params: type coercion, Path() constraints
# - Query params: Query() constraints, type coercion
# - Request body: Pydantic model validation
# - All errors → HTTP 422 Unprocessable Entity
# - No manual validation needed

Alias and deprecation

Use alias= in Query() or Field() to accept a different name in the request, and deprecated=True to mark old params.

from fastapi import FastAPI, Query
app = FastAPI()

@app.get("/items")
def get_items(
    q: str | None = Query(default=None, alias="search-query"),
    old: str | None = Query(default=None, deprecated=True),
):
    return {"q": q, "old": old}

# GET /items?search-query=python

Quick Check

How does FastAPI distinguish between a path parameter, a query parameter, and a request body?

Recap

Use Path()/Query() for parameter constraints. Nest Pydantic models for complex bodies. Mix path, query, and body parameters freely. UploadFile handles files; Form() handles HTML forms. FastAPI validates everything before your handler runs.

Free to start

Learn Python with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
76
Lessons
320

Frequently Asked Questions

Is the “Path Parameters, Query Params, and Request Bodies” lesson free?

Yes — the full text of “Path Parameters, Query Params, and Request Bodies” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO. The Python Academy course includes 4 lessons in total.

What will I learn in “Path Parameters, Query Params, and Request Bodies”?

Define typed parameters and request body schemas with Pydantic. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Path Parameters, Query Params, and Request Bodies” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. FastAPI Project Setup and First Endpoint
  2. Path Parameters, Query Params, and Request Bodies
  3. Dependency Injection and Authentication
  4. Async Endpoints and Database Integration
← Back to Python Academy