HTTPException
An HTTP exception you can raise in your own code to show errors to the client. Use this for client errors like invalid authentication, invalid data, or resource not found. This is not for server errors in your code (those should be handled differently).Constructor
int
required
HTTP status code to send to the client (e.g., 404, 401, 403, 400).
Any
default:"None"
Any data to be sent to the client in the
detail key of the JSON response. This can be a string, dict, list, or any JSON-serializable object.dict[str, str] | None
default:"None"
Any custom headers to send to the client in the response.
Response Format
When raised, HTTPException returns a JSON response with this structure:Common Use Cases
404 Not Found
401 Unauthorized
403 Forbidden
400 Bad Request
Usage Notes
- Can be raised from anywhere in your path operation or dependencies
- The exception is automatically caught by FastAPI and converted to a proper HTTP response
- Use appropriate status codes from the
statusmodule for better code readability - The
detailparameter supports any JSON-serializable data structure - Custom headers are useful for authentication challenges or additional metadata