""" Main FastAPI application for Newzy news application. """ from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException, status from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import ValidationError from config import settings from db.session import engine, Base from models.article import Article from models.author import Author from models.category import Category @asynccontextmanager async def lifespan(app: FastAPI): """Application lifespan event handlers.""" # On startup - create database tables Base.metadata.create_all(bind=engine) yield # On shutdown - cleanup if needed app = FastAPI( title=settings.APP_NAME, version=settings.APP_VERSION, description="Newzy News Application Backend API", lifespan=lifespan, ) # Exception handlers @app.exception_handler(ValidationError) async def validation_exception_handler(request, exc): """Handle Pydantic validation errors.""" return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": "Validation error", "message": str(exc)}, ) @app.exception_handler(Exception) async def general_exception_handler(request, exc): """Handle unhandled exceptions.""" return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"detail": "Internal server error"}, ) # Health check endpoint @app.get("/health", tags=["Health"]) async def health_check(): """Check if the application is running.""" return {"status": "healthy"} # Version endpoint @app.get("/api/v1/version", tags=["Info"]) async def get_version(): """Get application version information.""" return { "version": settings.APP_VERSION, "application": settings.APP_NAME, } # Placeholder routes for future implementation # (Models are defined but API endpoints will be added in subsequent milestones) if __name__ == "__main__": import uvicorn uvicorn.run( "main:app", host="0.0.0.0", port=8000, reload=settings.DEBUG, )