OnyxMetric
Integration Guides

FastAPI

Add OnyxMetric analytics to your FastAPI app

FastAPI renders HTML through Jinja2Templates, so the tag goes in the <head> of the base template your pages extend. Keep the site ID in a pydantic-settings class and register it as a Jinja global.

Copy your tracking snippet

In OnyxMetric, open your site's Site Settings and copy the tracking script. It looks like this:

<script src="https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID" async></script>

YOUR_SITE_ID is the numeric ID of your site.

Add the snippet to FastAPI

The script runs in a browser, so it only matters for routes that return template-rendered HTML. JSON endpoints have nothing for it to track.

Configure the site ID

pip install pydantic-settings jinja2
config.py
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=".env")

    onyxmetric_site_id: str = ""


settings = Settings()
.env
ONYXMETRIC_SITE_ID=YOUR_SITE_ID

Register it with Jinja

main.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

from config import settings

app = FastAPI()
templates = Jinja2Templates(directory="templates")
templates.env.globals["onyxmetric_site_id"] = settings.onyxmetric_site_id


@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
    return templates.TemplateResponse(request=request, name="index.html")

Edit the base template

templates/base.html
<head>
    <meta charset="utf-8">
    <title>{% block title %}My App{% endblock %}</title>

    {% if onyxmetric_site_id %}
    <script src="https://app.onyxmetric.com/api/script.js?siteId={{ onyxmetric_site_id }}" async></script>
    {% endif %}
</head>

With no ID set, the tag is skipped and local development stays untracked.

Check that it works

Load your live site and click through a few pages. Pageviews show up in the OnyxMetric dashboard within seconds.

If nothing arrives:

  • View the page source and search for script.js?siteId= to confirm the tag is present.
  • In the browser's Network tab, check that script.js returns 200 and that requests go to /api/track.
  • Turn off ad blockers, or proxy the script through your own domain.
  • Read script troubleshooting for other causes.

Troubleshooting

  • Tag missing: Settings() reads the environment at import time, so restart Uvicorn after changing the variable.
  • Several Jinja2Templates objects: globals belong to one environment. If routers build their own, set the global on each or share a single instance.
  • CSP middleware: allow app.onyxmetric.com in script-src and connect-src, or proxy the script.

Next steps

On this page