import uvicorn from fastapi import FastAPI, Request, status from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pathlib import Path from sqlalchemy.exc import SQLAlchemyError from app.api.routers import todo from app.core.config import settings from app.core.exceptions import TodoNotFoundException, ValidationError, DatabaseError app = FastAPI( title="Todo API", description="A simple Todo API built with FastAPI", version="0.1.0" ) # Exception handlers @app.exception_handler(TodoNotFoundException) async def todo_not_found_exception_handler(request: Request, exc: TodoNotFoundException): return JSONResponse( status_code=exc.status_code, content={"detail": exc.detail}, ) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": str(exc)}, ) @app.exception_handler(SQLAlchemyError) async def sqlalchemy_exception_handler(request: Request, exc: SQLAlchemyError): return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"detail": "Database error occurred"}, ) @app.exception_handler(Exception) async def general_exception_handler(request: Request, exc: Exception): return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"detail": "An unexpected error occurred"}, ) # Include routers app.include_router(todo.router, prefix="/api/v1") # Health check endpoint @app.get("/health", tags=["Health"]) async def health_check(): return {"status": "healthy"} if __name__ == "__main__": uvicorn.run( "main:app", host=settings.HOST, port=settings.PORT, reload=settings.DEBUG, )