skip to content

In FastAPI, why does GET /users/me return a 422 when /users/{user_id} with user_id: int is declared before it?

level: middleimportance: must knowfreq 60%

answer

  1. registration order decides
  2. placeholder matches any segment
  3. type check after matching
  4. fixed paths first

basics

~20 s

FastAPI tries routes in registration order and /users/{user_id} matches any single segment, including me; the int annotation is validated only after the route is chosen, so it answers 422 instead of falling through. Declare /users/me first.

solid answer

~40 s

Routes are tried in the order they were registered, and the first one whose path and method match handles the request. A plain `{user_id}` placeholder matches any one path segment, so `/users/me` matches `/users/{user_id}`. The `int` annotation is not part of matching: FastAPI validates it after the route is selected, so `"me"` fails conversion and the client gets a 422 with `loc` `["path", "user_id"]`; the later `/users/me` route is never tried. If `user_id` were a `str`, the wrong handler would run and answer 200, which is worse. The fix is to declare `/users/me` before `/users/{user_id}`; a Starlette path convertor such as `{user_id:int}` also works, at the cost of a 404 instead of a 422 for non-numeric IDs.

code

python · 13 lines
python
from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me")
async def read_me():
    return {"user": "the current user"}


@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id}

go deeper

for a junior

Remember that routes are tried in declaration order, so fixed paths like /users/me must be declared before /users/{user_id}.

for a middle

Explain that matching uses only the path pattern and method, that the annotation is validated after a route is chosen, and why the result is a 422 rather than a fall-through.

for a senior

Point out that a str parameter turns the 422 into a silent 200 from the wrong handler, compare reordering with a Starlette convertor, and back the order with a test per fixed path.

for a principal

Treat route-order rules as a codebase convention with a guard: a lint or test that fails when a fixed path is shadowed is cheaper than reviewers remembering it.

## How FastAPI picks a route A FastAPI app keeps its routes in a list, in the order the decorators ran. For each request it walks that list and asks every route whether it matches the path and the method: - **Full match**: path and method both match. The first full match handles the request and the walk stops. - **Partial match**: the path matches but the method does not. FastAPI remembers the first one and keeps looking; if no full match turns up, the request gets **405 Method Not Allowed** with an `Allow` header. - **No match**: the path does not match. If nothing matches at all, the answer is **404**. The important detail is what "the path matches" means. A placeholder such as `{user_id}` is compiled with Starlette's default `str` convertor, a regular expression that accepts any run of characters up to the next `/`. The parameter's **annotation plays no part in matching**. ## What happens to GET /users/me 1. The request path `/users/me` is compared with `/users/{user_id}`, registered first. The placeholder accepts `me`, the method is GET, so this is a full match. 2. FastAPI stops looking. The `/users/me` route further down the list is never considered. 3. FastAPI now binds parameters for the chosen route: it tries to turn `"me"` into an `int` and fails. 4. It answers **422** with `{"type": "int_parsing", "loc": ["path", "user_id"], ...}` and never calls either function. The 422 is the helpful version of this bug. With `user_id: str`, step 3 succeeds and `read_user("me")` runs, returning **200** with the wrong data, which can go unnoticed for a long time. ## Ways to fix it | Fix | Effect on /users/me | Effect on /users/abc | Notes | |---|---|---|---| | Declare `/users/me` first | handled by `read_me` | 422 from `read_user` | the documented approach | | Use `/users/{user_id:int}` | falls through to `read_me` | **404** | Starlette convertor; the schema path stays `/users/{user_id}` | | Validate with `Path(ge=1)` | still 422 | still 422 | constraints run after matching, so this does not help | Starlette's built-in convertors are `str`, `int`, `float`, `uuid` and `path`. A convertor changes the **regular expression** the route matches, so it is the only declaration that influences route selection; everything inside `Annotated` runs later. ## Related ordering rules - **Methods matter.** If `PUT /orders/{order_id}` is declared before `GET /orders/latest`, a GET to `/orders/latest` still reaches the GET route, because the PUT route is only a partial match. A POST to the same path gets 405 with `Allow: PUT`. - **Duplicates are silent.** Declaring the same method and path twice does not raise; the first registration always wins and the second function is dead code. - **Catch-alls go last.** A `{file_path:path}` route matches every deeper path under its prefix, so it belongs after the specific routes it would otherwise shadow. ## Diagnosing a shadowed route A shadowed route rarely announces itself. The schema at `/docs` lists both `/users/{user_id}` and `/users/me` as if both worked, so the evidence comes from elsewhere: 1. **The error names the wrong parameter.** A 422 whose `loc` is `["path", "user_id"]` on a request for `/users/me` proves the request landed on the user_id route. 2. **The registration order is visible.** `[route.path for route in app.routes]` lists the app's routes in the order they are tried, after the built-in docs routes. 3. **A log line in the fixed-path handler never fires.** If `read_me` is never called while clients hit `/users/me`, something registered earlier is catching the path. ## How to keep it from recurring - Group fixed paths such as `/users/me` and `/users/search` above parameterised ones in each module. - Add a test that requests every fixed path and asserts the expected handler answered, since the schema at `/docs` lists both routes and hides the shadowing. - Prefer typed identifiers such as `int` or `UUID` for path parameters: a shadowing bug then shows up as a 422 in the first test instead of as wrong data in production.

  • In FastAPI, why would you not always reach for `{user_id:int}` instead of reordering routes?
    The convertor makes a non-numeric ID a 404 instead of a 422 with a clear `loc`, so clients lose the explanation of what was wrong. The `:int` also does not appear in the generated schema, which still shows `/users/{user_id}`. Reordering keeps the validation error and is what the FastAPI docs prescribe; the convertor is a tool for when the order cannot be controlled.
  • In FastAPI, does `PUT /users/{user_id}` declared first shadow a later `GET /users/me`?
    No. A route whose path matches but whose method does not is only a partial match, so FastAPI keeps looking and the GET route is a full match. Shadowing only happens between routes that accept the same method. A method nobody accepts at that path gets 405 with an `Allow` header listing the methods of the first partial match.

A receptionist sends each visitor to the first desk whose sign fits, and only checks their ID once they are seated there; a visitor who would fit a later desk never gets to it, even if the ID check fails.

  • FastAPI sorts routes so that fixed paths always win over parameterised ones.
  • Annotating user_id as int keeps /users/me from matching the user_id route.
  • Adding Path(ge=1) to user_id lets /users/me fall through to the next route.
  • Declaring the same path operation twice raises an error at startup.
  • When validation fails on one route, FastAPI tries the next matching route.