45 lines
1.7 KiB
Python
45 lines
1.7 KiB
Python
# app/api/v1/endpoints/health.py
|
|
import logging
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy.sql import text
|
|
|
|
from app.database import get_db # Import the dependency function
|
|
from app.schemas.health import HealthStatus # Import the response schema
|
|
|
|
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"] # Group this endpoint in Swagger UI
|
|
)
|
|
async def check_health(db: AsyncSession = Depends(get_db)):
|
|
"""
|
|
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 503 Service Unavailable
|
|
raise HTTPException(
|
|
status_code=503,
|
|
detail="Database connection error: Unexpected result"
|
|
)
|
|
|
|
except Exception as e:
|
|
logger.error(f"Health check failed: Database connection error - {e}", exc_info=True) # Log stack trace
|
|
# Raise 503 Service Unavailable
|
|
raise HTTPException(
|
|
status_code=503,
|
|
detail=f"Database connection error: {e}"
|
|
) |