skip to content

In FastAPI, how do you restrict a path parameter to fixed values with an Enum, and capture a value containing slashes with :path?

level: juniorimportance: should knowfreq 35%

answer

  1. subclass str and Enum
  2. the member, not the string
  3. a Starlette convertor in the template
  4. percent-encoded dot segments

basics

~20 s

Annotate the path parameter with a class inheriting from str and Enum, so other values get a 422 and the docs list the choices; write {file_path:path} in the template so the parameter takes the rest of the URL, slashes included.

solid answer

~30 s

For fixed values, declare `class Category(str, Enum)` and annotate `category: Category`; FastAPI validates the segment against the members, passes the **enum member** to the function, answers 422 listing the allowed values otherwise, and shows them as a dropdown in `/docs`. For a value containing slashes, use Starlette's path convertor: `@app.get("/files/{file_path:path}")` gives `file_path` everything after `/files/`, such as `docs/2026/report.pdf`; a leading slash needs a double slash in the URL. Treat that value as untrusted: percent-encoded `..` segments reach the function, so resolve the path and check it stays under the base directory before opening anything.

code

python · 17 lines
python
from enum import Enum

from fastapi import FastAPI

app = FastAPI()


class Category(str, Enum):
    books = "books"
    music = "music"


@app.get("/categories/{category}")
async def list_category(category: Category):
    if category is Category.books:
        return {"category": category, "shelf": "A"}
    return {"category": category.value, "shelf": "B"}

go deeper

for a junior

Recall the two declarations: a class inheriting from str and Enum as the annotation, and {name:path} in the route template for values with slashes.

for a middle

Explain that the function receives the enum member, that invalid values get a 422 listing the choices, and that :path is a Starlette convertor the schema cannot express.

for a senior

Review any :path endpoint as untrusted input: percent-encoded dot segments reach the function, so resolve and contain the path, and place the catch-all after specific routes.

for a principal

Decide where hierarchical identifiers are allowed at all; a team rule of mapping keys to records instead of filesystem paths removes a whole class of traversal reviews.

## Fixed values with an Enum When a path segment can only take a few values, such as a catalogue category, declare an **enumeration** and use it as the annotation: - Inherit from both `str` and `Enum`, as in `class Category(str, Enum)`. The `str` base tells the generated schema that the values are strings, so the docs render them correctly. - Annotate the parameter with the class: `category: Category`. FastAPI then does three things with the declaration: 1. **Validates** the incoming segment against the member values. `/categories/films` gets a 422 whose message lists the choices: `Input should be 'books' or 'music'`, with `type` `enum`. 2. **Converts** a valid segment into the **enum member**, so the function receives `Category.books`, not the string `"books"`. You can compare it with `is Category.books` or read `.value` for the string. 3. **Documents** the allowed values as an `enum` in the schema, which Swagger UI shows as a dropdown. Returning an enum member in a response is fine: FastAPI serialises it to its value. The same annotation works for query parameters too. ## Values that contain slashes: the path convertor A normal placeholder like `{file_path}` matches one segment only, so `/files/docs/report.pdf` would not match `/files/{file_path}` at all and would answer 404. To capture the rest of the URL, add Starlette's **path convertor** in the template: ```python @app.get("/files/{file_path:path}") async def read_file(file_path: str): return {"file_path": file_path} ``` | Request | `file_path` receives | |---|---| | `/files/docs/2026/report.pdf` | `docs/2026/report.pdf` | | `/files//etc/hosts` | `/etc/hosts` (the double slash keeps a leading slash) | | `/files/%2E%2E/%2E%2E/etc/passwd` | `../../etc/passwd` | Points to remember: - The convertor is Starlette's, not part of the schema standard, so the docs still show a plain `{file_path}` parameter with no hint that it may contain slashes. - A `:path` route matches everything under its prefix. Declare more specific routes under the same prefix **before** it, because routes are tried in registration order. ## Reviewing a :path endpoint safely The last row of the table is the reason this convertor gets a security review. HTTP clients usually normalise literal `../` segments before sending, but a percent-encoded `%2E%2E` is decoded by the server into `..` and delivered to your function unchanged. If the code joins `file_path` onto a base directory and opens the result, a client can read files outside it. A defensive implementation: - resolves the joined path, for example `(BASE / file_path).resolve()`, and rejects it unless it `is_relative_to(BASE)`; - or maps `file_path` to stored records by key and never touches the filesystem with it; - or, for serving a directory of static files, uses the mount-based static file support instead of a hand-written route. ## Working with the enum member inside the function Because the function receives a member rather than a string, a few habits keep the code clear: - Compare with the member, `category is Category.books`, so a renamed value is caught by the editor rather than by a silent string mismatch. - Use `category.value` when you need the raw string, for example as a database filter or a cache key. - Add a member to the class to accept a new value; the validation, the 422 message and the dropdown in `/docs` all update from that one change. - Removing a member is a breaking change for clients that still send it, because they start receiving 422s. ## Testing these endpoints - Request one valid and one invalid Enum value, and assert the 422 lists the allowed values. - For a `:path` route, test a nested value, a value with a leading slash, and a percent-encoded `%2E%2E` segment, and assert the last one is refused by your containment check. - Request a specific route declared under the same prefix to prove the catch-all does not shadow it. ## Choosing between them - Use an **Enum** when the set of values is closed and known at deploy time; the 422 and the docs come for free. - Use **`:path`** only when the value really is hierarchical, and validate it as untrusted input. - Use a plain typed placeholder (`int`, `UUID`) for identifiers.

  • In FastAPI, why should the Enum used for a path parameter inherit from str as well as Enum?
    The `str` base makes the generated schema declare the values as strings, so the docs render the choices correctly, and it lets each member behave as its string value where a string is expected. FastAPI's documentation prescribes `class Name(str, Enum)` for exactly this reason. Validation and conversion to the member happen either way; the base type is about the schema.
  • In FastAPI, a /files/{file_path:path} route is declared before /files/recent; what happens to GET /files/recent?
    The `:path` route matches first, because its pattern accepts any remainder including `recent`, and routes are tried in registration order. The function receives `file_path` equal to `"recent"` and the later route is never reached. Declare `/files/recent` before the catch-all.

  • An Enum path parameter arrives in the function as a plain string.
  • A value outside the Enum makes FastAPI answer 404.
  • {file_path} without :path already captures values containing slashes.
  • A :path parameter can never contain dot-dot segments because clients normalise them.
  • The :path convertor is declared in the schema, so the docs explain it.