Last active
March 26, 2025 14:56
-
-
Save Jarmos-san/0b655a3f75b698833188922b714562e5 to your computer and use it in GitHub Desktop.
A simple FastAPI project with a health check route
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Entrypoint to invoke the FastAPI application service with.""" | |
from fastapi import FastAPI, status | |
from pydantic import BaseModel | |
import uvicorn | |
app = FastAPI() | |
class HealthCheck(BaseModel): | |
"""Response model to validate and return when performing a health check.""" | |
status: str = "OK" | |
@app.get( | |
"/health", | |
tags=["healthcheck"], | |
summary="Perform a Health Check", | |
response_description="Return HTTP Status Code 200 (OK)", | |
status_code=status.HTTP_200_OK, | |
response_model=HealthCheck, | |
) | |
def get_health() -> HealthCheck: | |
""" | |
## Perform a Health Check | |
Endpoint to perform a healthcheck on. This endpoint can primarily be used Docker | |
to ensure a robust container orchestration and management is in place. Other | |
services which rely on proper functioning of the API service will not deploy if this | |
endpoint returns any other HTTP status code except 200 (OK). | |
Returns: | |
HealthCheck: Returns a JSON response with the health status | |
""" | |
return HealthCheck(status="OK") | |
def main() -> None: | |
"""Entrypoint to invoke when this module is invoked on the remote server.""" | |
# See the official documentations on how "0.0.0.0" makes the service available on | |
# the local network - https://www.uvicorn.org/settings/#socket-binding | |
uvicorn.run("main:app", host="0.0.0.0") | |
if __name__ == "__main__": | |
main() | |
""" | |
To check if the API service works as expected, perform the following actions: | |
1. Run the API service by invoking this command - "python -m main". | |
2. If the service is running, open the URL "http://localhost:8000" in your browser. | |
3. With cURL, invoke this command: | |
"curl --include --request GET "http://localhost:8000/health" and you should | |
get a HTTP Status Code 200 OK message somewhere in it." | |
An example Dockerfile with a healthcheck capabilities enabled is available in this gist: | |
https://gist.github.com/Jarmos-san/11bf22c59d26daf0aa5223bdd50440da | |
""" |
Thanks for sharing the idea!
Thanks, its great!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good point.