0
0
FastAPIframework~5 mins

Health check endpoints in FastAPI

Choose your learning style9 modes available
Introduction

Health check endpoints help you quickly see if your web app is running well. They tell you if the app is alive and ready to handle requests.

You want to monitor if your app is up and running without logging in.
You need to connect your app with a load balancer that checks app health.
You want to automate alerts if your app stops working.
You want to test your app's basic response during deployment.
You want to check if your app dependencies like databases are reachable.
Syntax
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
async def health_check():
    return {"status": "ok"}

The endpoint is usually a simple GET request.

It returns a small JSON showing the app status.

Examples
Basic health check returning a simple status message.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
async def health_check():
    return {"status": "ok"}
Health check that also reports database connection status.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
async def health_check():
    return {"status": "ok", "database": "connected"}
Health check that includes uptime information.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
async def health_check():
    return {"status": "ok", "uptime": "24 hours"}
Sample Program

This FastAPI app has a health check endpoint at /health. When you visit this URL, it returns a JSON with {"status": "ok"}. This means the app is running fine.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
async def health_check():
    return {"status": "ok"}
OutputSuccess
Important Notes

Keep health check endpoints simple and fast to respond.

Use them with monitoring tools or load balancers to keep your app reliable.

You can add more checks like database or cache status if needed.

Summary

Health check endpoints show if your app is alive and working.

They usually return a simple JSON with status info.

Use them to help monitor and maintain your app easily.