diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 78a5f1f20a..6dafee060b 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -242,3 +242,27 @@ If you want to use the exception along with the same default exception handlers {* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *} 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. +