Охватываемые темы: Basic Usage, Status Codes, Error Details, Custom Headers.
Basic Usage
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/tasks/{task_id}")
def get_task(task_id: int):
task = db.get(task_id)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
return task
Status Codes
from fastapi import HTTPException
from starlette import status
raise HTTPException(status_code=400, detail="Bad request")
raise HTTPException(status_code=401, detail="Not authenticated")
raise HTTPException(status_code=403, detail="Access forbidden")
raise HTTPException(status_code=404, detail="Not found")
raise HTTPException(status_code=422, detail="Validation error")
# Or using constants
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
Error Details
raise HTTPException(
status_code=400,
detail={
"error": "validation_error",
"field": "title",
"message": "Title cannot be empty",
}
)
Custom Headers
raise HTTPException(
status_code=401,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
Custom Exception Handler
from fastapi import Request
from fastapi.responses import JSONResponse
class AppException(Exception):
def __init__(self, message: str, code: str):
self.message = message
self.code = code
@app.exception_handler(AppException)
async def app_exception_handler(request: Request, exc: AppException):
return JSONResponse(
status_code=400,
content={"error": exc.code, "message": exc.message},
)
# Usage
raise AppException(message="Task not found", code="task_not_found")
Global 404 Handler
from fastapi.responses import JSONResponse
@app.exception_handler(404)
async def not_found_handler(request: Request, exc):
return JSONResponse(
status_code=404,
content={"message": "Resource not found"},
)
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!