Skip to content

Install on FastAPI

View as Markdown

Add Reveata to pages a FastAPI app renders with Jinja2 templates or serves as static files, proxy it through your own domain, and credit payments to their visits.

On this page

FastAPI renders HTML with Jinja2 templates or serves a front-end build as static files. The snippet goes once in the file that renders <head> for every page.

Copy the snippet from your Reveata dashboard (it contains your website’s tracking id):

html
<script
  defer
  data-website-id="ws_your_tracking_id"
  src="https://reveata.com/js/script.js"
></script>

Add it to your site

With Jinja2 templates (Jinja2Templates(directory="templates")), paste the snippet before </head> in the base template your other templates extend, usually templates/base.html:

jinja
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{% block title %}My site{% endblock %}</title>
  <script defer data-website-id="ws_your_tracking_id" src="https://reveata.com/js/script.js"></script>
</head>
<body>
  {% block content %}{% endblock %}
</body>
</html>

With a front end served by FastAPI (app.mount("/", StaticFiles(directory="dist", html=True))), paste it in the front end’s index.html before you build. Its guide says where: React, Vue.

An API-only FastAPI backend serves no pages: put the snippet in the front end that calls it, wherever that is hosted.

Check it works

Deploy, open your site in a normal browser window with ad blockers turned off for it, then open Realtime in Reveata: your visit appears within a few seconds. If it doesn’t, follow Verify your installation. The script ignores localhost unless you add data-allow-localhost="true".

Serve it from your own domain

Two FastAPI routes can serve the script and pass events on with the visitor’s address and your proxy secret: see Proxy with FastAPI. If NGINX or Caddy sits in front of Uvicorn, it can do it instead: Proxy through NGINX, Proxy through Caddy. Or use the managed proxy: one DNS record, no code.

Revenue

First connect your payment provider in Reveata: see Connect a payment provider. Then pass the Reveata visitor id with each checkout, so the payment is credited to the visit that brought the buyer.

In the browser, send the ids with the request that starts the checkout:

js
const res = await fetch('/checkout', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ price_id: 'price_123', ...(window.reveata?.metadata?.() ?? {}) }),
});
window.location.href = (await res.json()).url;

On the server, put them in the Stripe Checkout Session’s metadata:

python
import stripe
from fastapi import Request
from pydantic import BaseModel


class CheckoutIn(BaseModel):
    price_id: str
    reveata_visitor_id: str | None = None
    reveata_session_id: str | None = None


@app.post("/checkout")
def checkout(body: CheckoutIn, request: Request):
    metadata = {
        k: v
        for k, v in {
            "reveata_visitor_id": body.reveata_visitor_id,
            "reveata_session_id": body.reveata_session_id,
        }.items()
        if v
    }
    session = stripe.checkout.Session.create(
        mode="payment",
        line_items=[{"price": body.price_id, "quantity": 1}],
        success_url=str(request.base_url) + "thanks?session_id={CHECKOUT_SESSION_ID}",
        metadata=metadata,
    )
    return {"url": session.url}

In a real app, check price_id against the prices you sell.

Payments from your own billing. If Reveata doesn’t connect to your provider, send each payment with the Payments API, for example with httpx:

python
import os, httpx

httpx.post(
    "https://reveata.com/api/v1/payments",
    headers={"Authorization": f"Bearer {os.environ['REVEATA_SITE_KEY']}"},
    json={
        "transactionId": f"order_{order.id}",
        "amount": float(order.total_without_tax),  # major units, e.g. 49.00
        "currency": "USD",
        "email": order.email,
        "visitorId": order.reveata_visitor_id,  # saved from the checkout request
    },
    timeout=10,
)

Goals

Add data-reveata-goal="signup" to a button or link in your templates, or call window.reveata?.('goal', 'signup') from your front-end code. See Custom goals.

Common pitfalls

  • Behind a proxy without --proxy-headers. For the proxy routes, run Uvicorn with --proxy-headers --forwarded-allow-ips set to your load balancer, or request.client.host is the load balancer’s address.
  • base_url with http. Behind HTTPS termination, request.base_url says http unless proxy headers are trusted (same flag).
  • Counting payments twice. With your payment provider connected in Reveata, don’t also send the same payments with the Payments API.

Was this helpful?