Skip to content

Commit 253ef83

Browse files
committed
added health check
1 parent e2ee945 commit 253ef83

1 file changed

Lines changed: 12 additions & 1 deletion

File tree

main.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from fastapi.exceptions import RequestValidationError
1010
from fastapi.staticfiles import StaticFiles
1111
from fastapi.templating import Jinja2Templates
12-
from sqlalchemy import select, func
12+
from sqlalchemy import select, func, text
1313
from sqlalchemy.ext.asyncio import AsyncSession
1414
from sqlalchemy.orm import selectinload
1515
from starlette.exceptions import HTTPException as StarletteHTTPException
@@ -35,6 +35,17 @@ async def lifespan(_app: FastAPI):
3535
app.include_router(users.router, prefix="/api/users", tags=["users"])
3636
app.include_router(posts.router, prefix="/api/posts", tags=["posts"])
3737

38+
@app.get("/health")
39+
async def health_check(db: Annotated[AsyncSession, Depends(get_db)]):
40+
try:
41+
await db.execute(text("SELECT 1"))
42+
except Exception as e:
43+
raise HTTPException(
44+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
45+
detail="Database is not available",
46+
) from e
47+
return {"status": "healthy"}
48+
3849

3950
@app.get("/", include_in_schema=False, name="home")
4051
@app.get("/posts", include_in_schema=False, name="posts")

0 commit comments

Comments
 (0)