Path & Query Params in FastAPI | Video 4 | CampusX
Based on CampusX's video on YouTube. If you like this content, support the original creators by watching, liking and subscribing to their content.
Use path parameters like `/patient/{patient_id}` to target a single resource based on a dynamic URL segment.
Briefing
FastAPI path parameters let clients pick a specific resource directly from the URL—turning one endpoint into a flexible “fetch/update/delete by ID” tool. In the example, an endpoint initially returned all patients, but adding a dynamic URL segment like `/patient/{patient_id}` allows requests such as `/patient/P003` or `/patient/P005` to return only the requested patient. The dynamic segment (the part that changes between requests) is the path parameter, and FastAPI passes it into the endpoint function as a typed argument (here, a string because IDs look like `P01`, `P002`, etc.). Inside the handler, the code loads the full patient dataset (via a utility function), checks whether the requested `patient_id` exists in the data dictionary, and returns the matching record; otherwise it returns an error message.
That basic approach works, but it has a practical flaw: even when a patient ID doesn’t exist, the response still comes back with HTTP 200, which misleads clients into thinking the request succeeded. The fix is to raise a proper HTTP error using FastAPI’s `HTTPException`. When the patient ID is missing, the endpoint now raises `HTTPException(status_code=404, detail="Patient not found")`, producing a correct 404 response and a structured error body. This change makes the API behavior consistent with HTTP semantics: successful requests return 2xx codes (like 200), missing resources return 404, and server-side problems return 5xx codes.
The next improvement focuses on API usability and documentation. FastAPI’s `Path` helper adds metadata—descriptions, examples, and optional validation constraints—so the interactive docs clearly show what the client should send. For the `patient_id` path parameter, adding a description and an example like `P01` makes the Swagger UI guidance more informative, and FastAPI can enforce constraints such as numeric ranges, string length limits, or regex patterns when applicable.
Finally, the transcript shifts to query parameters, which support optional “extra instructions” without changing the endpoint path. A new `/sort` endpoint accepts two query parameters: `sort_by` (required) and `order` (optional). `sort_by` can be `weight`, `height`, or `bmi`, while `order` can be `ascending` or `descending` with a default of `ascending`. The endpoint validates both inputs: if `sort_by` isn’t one of the allowed fields, it raises `HTTPException(status_code=400, detail=...)`; if `order` isn’t valid, it raises another 400. Once validated, it loads the patient data, sorts the records by the chosen field, and returns the sorted list—using the `reverse` flag to switch between ascending and descending order. The result is an endpoint that supports filtering-like behavior (sorting) through URL query strings, while keeping the core route stable.
Cornell Notes
Path parameters in FastAPI are dynamic URL segments used to identify a specific resource, such as `/patient/{patient_id}`. They enable targeted retrieval, updates, and deletes by passing the URL value into the endpoint function (typed as needed, e.g., string IDs like `P01`). A key correctness upgrade is raising `HTTPException` with the right status code—returning 404 when a patient ID doesn’t exist instead of incorrectly returning 200. FastAPI’s `Path` helper further improves documentation and can add validation metadata (descriptions, examples, constraints). Query parameters (`?sort_by=...&order=...`) provide optional extra behavior without changing the endpoint path, enabling sorting with input validation and sensible defaults.
How do path parameters work in FastAPI, and why are they useful for resource-specific endpoints?
What’s the practical problem with returning an error message while still sending HTTP 200, and how is it fixed?
What does FastAPI’s `Path` helper add beyond a plain function parameter?
How do query parameters differ from path parameters, and when should they be used?
How does the `/sort` endpoint validate inputs and choose sorting order?
Review Questions
- What is the difference between a path parameter and a query parameter in FastAPI, and how does each affect the URL structure?
- Why is raising `HTTPException(status_code=404, ...)` preferable to returning an error message with HTTP 200?
- In the sorting endpoint, what happens when `sort_by` is invalid or when `order` is omitted?
Key Points
- 1
Use path parameters like `/patient/{patient_id}` to target a single resource based on a dynamic URL segment.
- 2
Load-and-check logic can work for small datasets, but missing resources should trigger `HTTPException` with correct status codes (e.g., 404).
- 3
FastAPI’s `Path` helper improves Swagger documentation by adding descriptions and examples, and can enforce validation constraints.
- 4
Query parameters (`?key=value`) are best for optional behaviors such as sorting, filtering, searching, and pagination without changing the endpoint path.
- 5
Validate query parameters explicitly and return 400 for invalid `sort_by` or `order` values to keep client behavior predictable.
- 6
Provide defaults for optional query parameters (e.g., default `order=ascending`) so endpoints remain easy to call.
- 7
Sorting can be implemented by selecting the sort key from the query parameter and using a reverse flag to switch between ascending and descending order.