Skip to content

Commit c186e4e

Browse files
redjaxredjax
and
redjax
authored
Feat/improve fastapi (#208)
* feat(healthcheck): Improve healtcheck Add a jsonable_encoder() to encode healthcheck response. Switch response from a bare string to a JSONResponse() object, with a status.HTTP_200_OK status and X-HEALTHY header. * Repo/pdmlock (#206) * feat(settings): Add .vscode settings * feat(bump): Bump project version & tag * feat(lockfile): Update PDM lockfile --------- Co-authored-by: redjax <[email protected]> --------- Co-authored-by: redjax <[email protected]>
1 parent 604c6b3 commit c186e4e

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

red_utils/fastapi_utils/src/healthcheck.py

+20-5
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,18 @@
44
import logging
55

66
from fastapi import APIRouter, HTTPException, status
7+
from fastapi.encoders import jsonable_encoder
8+
from fastapi.responses import JSONResponse
79

810
router = APIRouter(tags=["util"], responses={404: {"description": "Not found"}})
911

1012

11-
## Define filter for pings to /healthy
12-
# https://stackoverflow.com/a/70810102
1313
class EndpointFilter(logging.Filter):
14+
"""Filter pings to /health.
15+
16+
https://stackoverflow.com/a/70810102
17+
"""
18+
1419
def filter(self, record: logging.LogRecord) -> bool:
1520
return record.args and len(record.args) >= 3 and record.args[2] != "/health"
1621

@@ -19,6 +24,16 @@ def filter(self, record: logging.LogRecord) -> bool:
1924
logging.getLogger("uvicorn.access").addFilter(EndpointFilter())
2025

2126

22-
@router.get("/health")
23-
async def healthy() -> str:
24-
return "healthy"
27+
@router.get("/health", summary="Healthcheck")
28+
async def healthy() -> JSONResponse:
29+
"""Respond to healthchecks.
30+
31+
Endpoint does not take any parameters or request bodies.
32+
33+
Response: a 200 'OK', with a response body containing 'healthy'.
34+
"""
35+
health: dict = jsonable_encoder({"healthy": True})
36+
response = JSONResponse(
37+
status_code=status.HTTP_200_OK, headers={"X-HEALTHY": "true"}, content=health
38+
)
39+
return response

0 commit comments

Comments
 (0)