Browse Source

Add example for validating path parameters in error handling docs

pull/15355/head
Herbert Moses 3 months ago
parent
commit
4219e01f4a
  1. 24
      docs/en/docs/tutorial/handling-errors.md

24
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] *} {* ../../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. 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.

Loading…
Cancel
Save