Performance: Path parameter types and validation
This affects server response time and client perceived latency by validating and parsing path parameters efficiently before processing the request.
from fastapi import FastAPI app = FastAPI() @app.get('/items/{item_id}') async def read_item(item_id: int): # FastAPI validates and converts automatically 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, manual parsing later try: item_id_int = int(item_id) except ValueError: return {'error': 'Invalid item_id'} return {'item_id': item_id_int}
| Pattern | Server Processing | Validation Speed | Error Handling | Verdict |
|---|---|---|---|---|
| Manual string parsing | High CPU use per request | Slow, done at runtime | Delayed error response | [X] Bad |
| FastAPI type annotations | Low CPU use, automatic | Fast, built-in validation | Immediate error response | [OK] Good |
Path() with keyword arguments like ge (greater or equal) for minimum values.ge=1, not min, minimum, or min_value.from fastapi import FastAPI, Path
app = FastAPI()
@app.get('/users/{user_id}')
async def get_user(user_id: int = Path(ge=1, le=10)):
return {"user_id": user_id}
What will be the response if the client requests /users/15?user_id must be an integer between 1 and 10 inclusive./users/15, which is outside the allowed range (greater than 10).from fastapi import FastAPI, Path
app = FastAPI()
@app.get('/items/{item_id}')
async def read_item(item_id: str = Path(gt=0)):
return {"item_id": item_id}item_id is typed as str but uses gt=0 which means greater than 0, a numeric constraint.gt apply only to numbers, not strings, causing a validation error.product_id which must be an integer between 100 and 999 inclusive. If the value is invalid, FastAPI should reject the request automatically. Which of the following is the best way to declare this parameter?ge (greater or equal) and le (less or equal) for inclusive range validation.ge=100 and le=999 which matches the requirement exactly. The remaining options use invalid keywords or exclusive bounds. def get_product(product_id: int = Path(gt=100, lt=999)): uses exclusive bounds which exclude 100 and 999.Pass the test and this pattern moves unknown