
Create a simple Todo API with FastAPI and SQLite with CRUD functionality, health check, error handling, and API documentation.
59 lines
2.0 KiB
Python
59 lines
2.0 KiB
Python
from fastapi import FastAPI, Request, status
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from sqlalchemy.exc import SQLAlchemyError
|
|
|
|
|
|
class TodoException(Exception):
|
|
"""Base exception class for the Todo application."""
|
|
|
|
def __init__(self, status_code: int, detail: str):
|
|
self.status_code = status_code
|
|
self.detail = detail
|
|
|
|
|
|
def add_exception_handlers(app: FastAPI) -> None:
|
|
"""
|
|
Add exception handlers to the FastAPI application.
|
|
|
|
Args:
|
|
app: The FastAPI application instance.
|
|
"""
|
|
|
|
@app.exception_handler(TodoException)
|
|
async def todo_exception_handler(request: Request, exc: TodoException):
|
|
"""Handle custom TodoException."""
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content={"detail": exc.detail},
|
|
)
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_exception_handler(
|
|
request: Request,
|
|
exc: RequestValidationError
|
|
):
|
|
"""Handle request validation errors."""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
content={
|
|
"detail": "Validation error",
|
|
"errors": exc.errors(),
|
|
},
|
|
)
|
|
|
|
@app.exception_handler(SQLAlchemyError)
|
|
async def sqlalchemy_exception_handler(request: Request, exc: SQLAlchemyError):
|
|
"""Handle SQLAlchemy errors."""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
content={"detail": "Database error. Please try again later."},
|
|
)
|
|
|
|
@app.exception_handler(Exception)
|
|
async def general_exception_handler(request: Request, exc: Exception):
|
|
"""Handle all other exceptions."""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
content={"detail": "Internal server error. Please try again later."},
|
|
) |