← Back to FastAPI, page 1

fastapi-0002 · Easy fresher

How do path parameters work in FastAPI, and how does type conversion and validation happen?

Path parameters are parts of the URL declared in the route string, such as /students/{roll_no}, and received as function arguments with the same name. The type hint decides conversion and validation: roll_no: int turns "42" into 42 and returns a 422 error for "abc". Route order matters, so fixed paths like /students/me must be declared before /students/{roll_no}.

Full answer

A path parameter is a variable part of the URL path:

python
@app.get("/students/{roll_no}")
def get_student(roll_no: int): ...

What happens on GET /students/42:

  1. Starlette matches the route and extracts "42" as a string.
  2. FastAPI sees the int annotation and asks Pydantic to convert it. roll_no arrives as the integer 42.
  3. On GET /students/abc, conversion fails and FastAPI returns 422 Unprocessable Content with a JSON body describing the error (int_parsing, location ["path", "roll_no"]).

Supported types include int, float, str, bool, uuid.UUID, datetime.date, Enum subclasses and Literal. Extra constraints come from Path():

python
from typing import Annotated
from fastapi import Path
def get_student(roll_no: Annotated[int, Path(ge=1, le=9999)]): ...

Route order: routes are matched in the order they are declared. If /students/{roll_no} comes first, a request to /students/me tries to parse "me" as an int and fails with 422. Declare /students/me before the parameterised route.

Paths that contain slashes, such as file paths, need the :path converter: /files/{file_path:path}.

Path parameters are always required; a URL without that segment simply matches a different route or returns 404.

python
from typing import Annotated

from fastapi import FastAPI, Path
from fastapi.testclient import TestClient

app = FastAPI()


@app.get("/students/me")
def current_student():
    return {"roll_no": 7, "who": "me"}


@app.get("/students/{roll_no}")
def get_student(roll_no: Annotated[int, Path(ge=1, le=9999)]):
    return {"roll_no": roll_no, "type": type(roll_no).__name__}


@app.get("/files/{file_path:path}")
def read_file(file_path: str):
    return {"file_path": file_path}


c = TestClient(app)
print(c.get("/students/42").json())
print(c.get("/students/me").json())
bad = c.get("/students/abc")
print(bad.status_code, bad.json()["detail"][0]["type"], bad.json()["detail"][0]["loc"])
print(c.get("/students/0").json()["detail"][0]["msg"])
print(c.get("/files/reports/2026/term1.pdf").json())

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'roll_no': 42, 'type': 'int'} {'roll_no': 7, 'who': 'me'} 422 int_parsing ['path', 'roll_no'] Input should be greater than or equal to 1 {'file_path': 'reports/2026/term1.pdf'}

Key points

  • Declared in the route string and received by name
  • Type hints convert and validate; failure returns 422
  • Path() adds constraints like ge and le
  • Declare fixed routes before parameterised ones
  • Use {name:path} for values that contain slashes

Common mistakes

  • Declaring /students/{id} before /students/me
  • Expecting a 400 instead of 422 for a type mismatch
  • Validating ranges by hand instead of using Path(ge=..., le=...)
  • Forgetting {name:path} for values with slashes

Follow-ups

  • How would you restrict a path parameter to a fixed set of values?
  • What does the 422 response body contain?
  • How is a path parameter different from a query parameter?

Tips

  • Walk through the conversion step
  • Mention the route order trap with a concrete example
  • Use Annotated with Path for constraints, the current recommended style