In this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.
In this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.
### Handling Validation for Path Parameters
In real-world applications, you may need to validate input values beyond basic type checking.
For example, ensuring that an ID is a positive number:
```python
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
if user_id <= 0:
raise HTTPException(
status_code=400,
detail="User ID must be a positive integer"
)
return {"user_id": user_id}
```
This ensures that invalid values are handled gracefully and provides clear feedback to API clients.
You can also use validation libraries like Pydantic for more complex constraints.