Docs/FastAPI

FastAPI

Add monitoring to your FastAPI app. Async health endpoint, APScheduler heartbeats, and status badge.

1

Health endpoint

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

Heartbeat push (optional)

Use APScheduler to push heartbeats every 5 minutes. Install dependencies first:

pip install apscheduler httpx
import os
import time
import httpx
from datetime import datetime
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from contextlib import asynccontextmanager

BLUEMONITOR_API_KEY = os.getenv("BLUEMONITOR_API_KEY")

async def send_heartbeat():
    checks = {}

    # Database check
    db_start = time.monotonic()
    try:
        await database.execute("SELECT 1")
        checks["database"] = {
            "status": "ok",
            "latency": round((time.monotonic() - db_start) * 1000),
        }
    except Exception as e:
        checks["database"] = {
            "status": "error",
            "latency": round((time.monotonic() - db_start) * 1000),
            "message": str(e),
        }

    has_error = any(c["status"] == "error" for c in checks.values())

    async with httpx.AsyncClient() as client:
        await client.post(
            "https://www.bluemonitor.org/api/v1/heartbeat",
            headers={"Authorization": f"Bearer {BLUEMONITOR_API_KEY}"},
            json={
                "domain": "yourapp.com",
                "status": "error" if has_error else "ok",
                "timestamp": datetime.utcnow().isoformat(),
                "checks": checks,
            },
        )

@asynccontextmanager
async def lifespan(app):
    scheduler = AsyncIOScheduler()
    scheduler.add_job(send_heartbeat, "interval", minutes=5)
    scheduler.start()
    await send_heartbeat()  # Send on startup
    yield
    scheduler.shutdown()

app = FastAPI(lifespan=lifespan)
3

Status badge

[![Status](https://www.bluemonitor.org/api/badge/your-domain-com)](https://www.bluemonitor.org/status/your-domain-com)
4

Bot tracking

PRO

Track which search engines, AI crawlers, and social bots visit your app. Add bot detection middleware to report visits to BlueMonitor. Requires a Pro plan.

FastAPI middleware

import re, os, httpx
from starlette.middleware.base import BaseHTTPMiddleware

BOT_PATTERNS = [
    (re.compile(r"Googlebot", re.I), "googlebot", "search_engine"),
    (re.compile(r"bingbot", re.I), "bingbot", "search_engine"),
    (re.compile(r"GPTBot", re.I), "gptbot", "ai_crawler"),
    (re.compile(r"ClaudeBot", re.I), "claudebot", "ai_crawler"),
    (re.compile(r"PerplexityBot", re.I), "perplexitybot", "ai_crawler"),
    (re.compile(r"Twitterbot", re.I), "twitterbot", "social"),
    (re.compile(r"facebookexternalhit", re.I), "facebookbot", "social"),
    (re.compile(r"AhrefsBot", re.I), "ahrefsbot", "seo"),
]

def identify_bot(ua: str):
    for pattern, name, category in BOT_PATTERNS:
        if pattern.search(ua):
            return {"name": name, "category": category}
    return None

class BotTrackingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        ua = request.headers.get("user-agent", "")
        bot = identify_bot(ua)
        if bot:
            try:
                async with httpx.AsyncClient() as client:
                    await client.post(
                        "https://www.bluemonitor.org/api/v1/bot-visits",
                        headers={
                            "Authorization": f"Bearer {os.getenv('BLUEMONITOR_API_KEY')}"
                        },
                        json={
                            "domain": "yourapp.com",
                            "visits": [{
                                "bot_name": bot["name"],
                                "bot_category": bot["category"],
                                "path": str(request.url.path),
                                "user_agent": ua,
                            }],
                        },
                        timeout=5,
                    )
            except Exception:
                pass
        return await call_next(request)

app.add_middleware(BotTrackingMiddleware)

View results in your dashboard under Bot Tracking.

Using an AI coding tool?

Paste this URL in Claude, Cursor, or Copilot and it will set up monitoring for your FastAPI app automatically.

https://www.bluemonitor.org/llm-fastapi.txt

Next steps