Performance: Path parameters
Path parameters affect the routing speed and server response time, impacting how quickly the server matches URLs to handlers.
from fastapi import FastAPI, Path app = FastAPI() @app.get('/items/{item_id}') async def read_item(item_id: int = Path(..., gt=0)): # Type and constraint validation improves routing return {"item_id": item_id}
from fastapi import FastAPI app = FastAPI() @app.get('/items/{item_id}') async def read_item(item_id: str): # No type validation or constraints return {"item_id": item_id}
| Pattern | Routing Cost | Validation Cost | Server Processing | Verdict |
|---|---|---|---|---|
| Generic string path parameter | High (broad matching) | Low (simple) | Moderate | [X] Bad |
| Typed path parameter with constraints | Low (precise matching) | Moderate (validation) | Low | [OK] Good |
item_id in FastAPI?/users/42?
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
async def read_user(user_id: int):
return {"user_id": user_id}user_id is declared as int, so FastAPI converts the string "42" from the URL to integer 42.from fastapi import FastAPI
app = FastAPI()
@app.get("/products/{product_id}")
async def get_product(product_id):
return {"product": product_id}product_id lacks a type hint, so FastAPI treats it as a string by default but it's best practice to specify type.category (string) and item_id (integer). Which of the following is the correct way to define this route and function?category then item_id. The function parameters must match this order and names.str and int) and async function, which is recommended in FastAPI.Pass the test and this pattern moves unknown