# app/api/v1/endpoints/health.py import logging from fastapi import APIRouter, Depends from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql import text from app.database import get_transactional_session from app.schemas.health import HealthStatus from app.core.exceptions import DatabaseConnectionError logger = logging.getLogger(__name__) router = APIRouter() @router.get( "/health", response_model=HealthStatus, summary="Perform a Health Check", description="Checks the operational status of the API and its connection to the database.", tags=["Health"] ) async def check_health(db: AsyncSession = Depends(get_transactional_session)): """ Health check endpoint. Verifies API reachability and database connection. """ try: # Try executing a simple query to check DB connection result = await db.execute(text("SELECT 1")) if result.scalar_one() == 1: logger.info("Health check successful: Database connection verified.") return HealthStatus(status="ok", database="connected") else: # This case should ideally not happen with 'SELECT 1' logger.error("Health check failed: Database connection check returned unexpected result.") raise DatabaseConnectionError("Unexpected result from database connection check") except Exception as e: logger.error(f"Health check failed: Database connection error - {e}", exc_info=True) raise DatabaseConnectionError(str(e))