β οΈ Path Parameter Conflict (Route Hijacking) β With Query Params
FastAPI matches routes using the path only, not parameter names or query parameters.
π Query parameters (?category=...) do NOT help FastAPI choose between routes.
β Conflicting Example
@app.get("/books/{book_title}")
@app.get("/books/{book_author}")Both match:
/books/somethingπ FastAPI cannot distinguish them
π The first one defined captures all requests
π The second route never runs (hijacked)
β οΈ Why Query Parameters Didnβt Help
Even if this endpoint expects a query param:
@app.get("/books/{book_author}")
async def read_author_and_category(book_author: str, category: str):Request:
/books/Author One?category=scienceπ« FastAPI still matches only by:
/books/Author Oneπ It ignores ?category=science during routing
π So the request may go to /books/{book_title} instead
β
Why Adding / Worked
Changing to:
@app.get("/books/{book_author}/")creates a different path:
/books/something/Now FastAPI can distinguish:
/books/something
/books/something/π The correct endpoint receives the request.
β οΈ Important Caution
Query parameters do NOT affect route matching
Parameter names do NOT matter
Trailing slash creates a new route but can confuse users
Order and path structure matter most
β Best Practice
Use clear, unique paths instead of relying on /:
/books/title/{book_title}
/books/author/{book_author}π Quick Rule
π Routing = based on path only
π Query params are processed after a route is selected
π Use distinct endpoints to avoid hijacking
π Clean paths prevent confusing bugs in real APIs