Performance: Route ordering and priority
This affects how quickly the server matches incoming requests to the correct route, impacting response time and server throughput.
from fastapi import FastAPI app = FastAPI() @app.get("/users/me") async def read_user_me(): return {"user": "current user"} @app.get("/{item_id}") async def read_item(item_id: str): return {"item_id": item_id}
from fastapi import FastAPI app = FastAPI() @app.get("/users/me") async def read_user_me(): return {"user": "current user"} @app.get("/{item_id}") async def read_item(item_id: str): return {"item_id": item_id}
| Pattern | Route Checks | Unnecessary Matches | Response Delay | Verdict |
|---|---|---|---|---|
| Generic route before specific | High (checks all routes until match) | Yes (generic route matches specific paths first, blocking specific routes) | Noticeable delay on specific routes | [X] Bad |
| Specific route before generic | Low (matches specific routes immediately) | None | Minimal delay | [OK] Good |
/users/me is matched before the dynamic route /users/{user_id}?/users/me is more specific than the dynamic /users/{user_id}./users/me matches correctly, it must be defined before the dynamic route./items/special?
from fastapi import FastAPI
app = FastAPI()
@app.get('/items/{item_id}')
async def read_item(item_id: str):
return {'item_id': item_id}
@app.get('/items/special')
async def read_special():
return {'message': 'Special item'}/items/{item_id} is defined before the specific /items/special route./items/special matches the dynamic route first, returning {'item_id': 'special'}.@app.get('/products/{product_id}')
async def get_product(product_id: int):
return {'product_id': product_id}
@app.get('/products/latest')
async def get_latest_product():
return {'product': 'latest'}
When you request /products/latest, you get a 422 validation error. What is the likely cause?product_id: int is defined first, so FastAPI tries to match /products/latest here and convert 'latest' to int./files/{file_path:path} to serve any file path dynamically
- /files/download to trigger a download action
How should you order these routes to ensure /files/download works correctly without being captured by the dynamic route?{file_path:path} captures all paths under /files/, including 'download'./files/download matches the specific route, define it before the dynamic catch-all route.Pass the test and this pattern moves unknown