Get AI summaries of any video or article — Sign up free
Path & Query Params in FastAPI | Video 4 | CampusX thumbnail

Path & Query Params in FastAPI | Video 4 | CampusX

CampusX·
4 min read

Based on CampusX's video on YouTube. If you like this content, support the original creators by watching, liking and subscribing to their content.

TL;DR

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?

Path parameters are dynamic segments inside the URL path, like `/patient/{patient_id}`. When a client calls `/patient/P003`, FastAPI extracts `P003` from the URL and passes it into the endpoint function as an argument. This pattern is ideal when the API needs to operate on one specific resource (fetch/update/delete) rather than returning everything. In the example, the handler loads all patients, checks whether the requested `patient_id` exists in the dataset dictionary, and returns only that patient’s record.

What’s the practical problem with returning an error message while still sending HTTP 200, and how is it fixed?

If the endpoint returns a JSON error like “Patient not found” but still uses HTTP 200, clients may treat the request as successful. The fix is to raise FastAPI’s `HTTPException` with the correct status code. When the patient ID is missing, the endpoint raises `HTTPException(status_code=404, detail="Patient not found")`, producing a proper 404 response and a structured error body.

What does FastAPI’s `Path` helper add beyond a plain function parameter?

`Path` adds metadata and validation hints for path parameters. By using `Path(...)`, developers can attach a `description` and `example` so the interactive docs (Swagger UI) clearly show what the client should send (e.g., `patient_id` example `P01`). It can also enforce constraints such as numeric ranges, string length limits, or regex patterns when the parameter type supports it.

How do query parameters differ from path parameters, and when should they be used?

Query parameters come after `?` in the URL and are used for optional “extra instructions” like sorting, filtering, searching, or pagination while keeping the endpoint path stable. They’re ideal when the client may or may not request additional behavior. In the transcript, sorting is implemented via `/sort?sort_by=height&order=descending`, where `order` is optional and defaults to ascending.

How does the `/sort` endpoint validate inputs and choose sorting order?

The endpoint defines allowed values for `sort_by` (`weight`, `height`, `bmi`). If `sort_by` isn’t in the allowed set, it raises `HTTPException(status_code=400, detail="Invalid field...")`. For `order`, it allows `ascending` and `descending`; invalid values trigger another 400. Sorting is then performed by extracting values from the patient data and sorting by the selected key. The code uses a `reverse` flag: `reverse=True` for descending and `reverse=False` for ascending.

Review Questions

  1. What is the difference between a path parameter and a query parameter in FastAPI, and how does each affect the URL structure?
  2. Why is raising `HTTPException(status_code=404, ...)` preferable to returning an error message with HTTP 200?
  3. In the sorting endpoint, what happens when `sort_by` is invalid or when `order` is omitted?

Key Points

  1. 1

    Use path parameters like `/patient/{patient_id}` to target a single resource based on a dynamic URL segment.

  2. 2

    Load-and-check logic can work for small datasets, but missing resources should trigger `HTTPException` with correct status codes (e.g., 404).

  3. 3

    FastAPI’s `Path` helper improves Swagger documentation by adding descriptions and examples, and can enforce validation constraints.

  4. 4

    Query parameters (`?key=value`) are best for optional behaviors such as sorting, filtering, searching, and pagination without changing the endpoint path.

  5. 5

    Validate query parameters explicitly and return 400 for invalid `sort_by` or `order` values to keep client behavior predictable.

  6. 6

    Provide defaults for optional query parameters (e.g., default `order=ascending`) so endpoints remain easy to call.

  7. 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.

Highlights

Adding `{patient_id}` to the route turns a “return all patients” endpoint into a “return one patient” endpoint via URLs like `/patient/P003`.
Correct error semantics matter: raising `HTTPException(status_code=404, detail="Patient not found")` prevents misleading HTTP 200 responses.
`Path` and `Query` helpers make APIs easier to use by enriching interactive docs with descriptions and examples.
Query parameters enable flexible sorting through URLs like `/sort?sort_by=height&order=descending`, with `order` defaulting to ascending when omitted.

Topics

  • Path Parameters
  • HTTPException 404
  • FastAPI Path Metadata
  • Query Parameters
  • Sorting with Query Params

Mentioned