Automated Action cd7c0162fe Create REST API with FastAPI and SQLite
- Implemented project structure with FastAPI framework
- Set up SQLite database with SQLAlchemy ORM
- Created Alembic for database migrations
- Implemented Item model and CRUD operations
- Added health check endpoint
- Added error handling
- Configured API documentation with Swagger UI

generated with BackendIM... (backend.im)
2025-05-13 15:58:51 +00:00

53 lines
1.8 KiB
Python

from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
class AppError(Exception):
"""Base error class for the application"""
def __init__(self, message: str, status_code: int):
self.message = message
self.status_code = status_code
super().__init__(self.message)
class NotFoundError(AppError):
"""Resource not found error"""
def __init__(self, message: str):
super().__init__(message, status_code=status.HTTP_404_NOT_FOUND)
class ValidationError(AppError):
"""Data validation error"""
def __init__(self, message: str):
super().__init__(message, status_code=status.HTTP_400_BAD_REQUEST)
class DatabaseError(AppError):
"""Database-related error"""
def __init__(self, message: str):
super().__init__(message, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
def add_error_handlers(app: FastAPI) -> None:
"""Configure exception handlers for the app"""
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.message}
)
@app.exception_handler(status.HTTP_404_NOT_FOUND)
async def not_found_handler(request: Request, exc: Exception) -> JSONResponse:
return JSONResponse(
status_code=status.HTTP_404_NOT_FOUND,
content={"detail": "Resource not found"}
)
@app.exception_handler(status.HTTP_500_INTERNAL_SERVER_ERROR)
async def server_error_handler(request: Request, exc: Exception) -> JSONResponse:
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Internal server error"}
)