|
| 1 | +# FastAPI Day 05: HTTP Status Codes and Error Handling |
| 2 | + |
| 3 | +Welcome to **Day 05** of the FastAPI tutorial! Today you'll learn how to handle HTTP status codes, create custom error responses, and manage exceptions in your API endpoints. |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## What You'll Learn |
| 8 | + |
| 9 | +- How to use and return appropriate HTTP status codes |
| 10 | +- How to create and use custom exception classes |
| 11 | +- How to handle validation and business logic errors gracefully |
| 12 | +- How to implement global exception handlers for consistent error responses |
| 13 | +- How to write automated tests for error handling |
| 14 | + |
| 15 | +--- |
| 16 | + |
| 17 | +## Key Concepts |
| 18 | + |
| 19 | +### 1. HTTP Status Codes |
| 20 | + |
| 21 | +- **HTTP status codes** communicate the result of an API request. |
| 22 | +- Use codes like `200 OK`, `201 Created`, `404 Not Found`, `409 Conflict`, `422 Unprocessable Entity`, and `500 Internal Server Error` to indicate different outcomes. |
| 23 | + |
| 24 | +Example status codes: |
| 25 | +``` |
| 26 | +201 Created - When a new item or order is successfully created |
| 27 | +404 Not Found - When a requested resource does not exist |
| 28 | +409 Conflict - When there is a duplicate or business logic conflict |
| 29 | +422 Unprocessable Entity - When validation fails |
| 30 | +500 Internal Server Error - For unexpected errors |
| 31 | +``` |
| 32 | + |
| 33 | +### 2. Custom Exception Classes |
| 34 | + |
| 35 | +- Define custom exception classes for common error scenarios (e.g., not found, insufficient stock, duplicate item). |
| 36 | +- Inherit from FastAPI's `HTTPException` for easy integration. |
| 37 | + |
| 38 | +Example custom exception: |
| 39 | +``` |
| 40 | +class ItemNotFoundError(HTTPException): |
| 41 | + def __init__(self, item_id: int): |
| 42 | + super().__init__( |
| 43 | + status_code=status.HTTP_404_NOT_FOUND, |
| 44 | + detail=f"Item with ID {item_id} not found", |
| 45 | + ) |
| 46 | +``` |
| 47 | + |
| 48 | +### 3. Exception Handlers |
| 49 | + |
| 50 | +- Use FastAPI's `@app.exception_handler` to create global handlers for your custom exceptions. |
| 51 | +- Return structured error responses with details, error type, and timestamps. |
| 52 | + |
| 53 | +Example handler: |
| 54 | +``` |
| 55 | +@app.exception_handler(ItemNotFoundError) |
| 56 | +async def item_not_found_handler(request: Request, exc: ItemNotFoundError): |
| 57 | + return JSONResponse( |
| 58 | + status_code=exc.status_code, |
| 59 | + content={ |
| 60 | + "error": "Item Not Found", |
| 61 | + "message": exc.detail, |
| 62 | + "timestamp": datetime.now().isoformat(), |
| 63 | + "path": str(request.url.path) |
| 64 | + } |
| 65 | + ) |
| 66 | +``` |
| 67 | + |
| 68 | +### 4. Validation and Business Logic Errors |
| 69 | + |
| 70 | +- Use Pydantic for request validation and raise custom errors for business logic issues (e.g., insufficient stock, invalid transitions). |
| 71 | +- Customize error responses for better client experience. |
| 72 | + |
| 73 | +Example validation error: |
| 74 | +``` |
| 75 | +@app.exception_handler(RequestValidationError) |
| 76 | +async def request_validation_error_handler(request: Request, exc: RequestValidationError): |
| 77 | + return JSONResponse( |
| 78 | + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, |
| 79 | + content={ |
| 80 | + "error": "Validation Error", |
| 81 | + "message": "Invalid request data", |
| 82 | + "details": exc.errors(), |
| 83 | + "timestamp": datetime.now().isoformat(), |
| 84 | + "path": str(request.url.path) |
| 85 | + } |
| 86 | + ) |
| 87 | +``` |
| 88 | + |
| 89 | +### 5. Logging and Monitoring |
| 90 | + |
| 91 | +- Use Python's `logging` module to log errors and important events. |
| 92 | +- Logging helps with debugging and monitoring your API in production. |
| 93 | + |
| 94 | +--- |
| 95 | + |
| 96 | +## Next Steps |
| 97 | + |
| 98 | +- Try sending requests that trigger different error scenarios (e.g., not found, duplicate, validation errors). |
| 99 | +- Explore the code to see how exceptions and handlers are implemented. |
| 100 | +- Run the tests to ensure error handling works as expected! |
| 101 | + |
| 102 | +--- |
| 103 | + |
| 104 | +**Tip:** FastAPI’s automatic docs are available at `/api/docs` when you run your app. |
| 105 | + |
| 106 | +--- |
0 commit comments