Routes Match in Declaration Order, So a Dynamic Path Can Shadow a Static One
Most web frameworks test routes from top to bottom and use the first one that matches. A dynamic route such as /items/{item_id} matches /items/search too, with item_id = "search", so if it is declared first the static /items/search route is never reached. The request either hits the wrong handler or fails validation (422 in FastAPI when item_id must be an integer). Declaring specific static paths before generic dynamic ones avoids it.
FastAPI
@app.get("/items/search") # static: declare first
def search_items(q: str): ...
@app.get("/items/{item_id}") # dynamic: matches anything else
def read_item(item_id: int): ...
Reversed, GET /items/search?q=pen reaches read_item, which rejects "search" as an integer: a confusing 422 for a route that "exists". The same rule applies across APIRouters: routes are added in include_router() order.
Rails
resources :books # defines books/:id
get "books/search", to: "dashboard/books#search" # never reached
resources :books creates GET /books/:id, which matches /books/search first and sends it to BooksController#show with id = "search". Move the custom route above resources, or nest it as a collection route:
resources :books do
get :search, on: :collection
end
Django
Django also tries urlpatterns in order. A converter limits the damage (<int:pk> doesn't match search), but <slug:slug> or <str:name> would.
References
- FastAPI MOC - hub for FastAPI notes.
- FastAPI Reads Each Parameter from the Path, Query, Body or Headers According to Its Declaration - how path parameters are captured.
- Django Path Converters Validate and Type URL Segments Before the View Runs - converters as a filter on matching.
- FastAPI documentation: Path Parameters, order matters - the static-before-dynamic rule.
- Rails Guides: Rails Routing from the Outside In - route priority and collection routes.
Review cards
Flashcard Why is it important to declare specific static paths before generic dynamic ones?
To ensure that static paths are matched before dynamic ones, preventing dynamic routes from shadowing static ones and causing issues like incorrect handler invocation or validation errors.
Flashcard Why can a shadowed route still pass its unit tests?
Calling the handler function directly bypasses the router. Only a request through the router (TestClient, request specs) shows another route catching the path first.
Flashcard GET /items/search?q=pen returns 422 in FastAPI, although the search route exists. Why?
/items/{item_id} is declared first: it matches /items/search with item_id = "search" and rejects that as an integer. Declare the static route first.