πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Add guides section to API documentation
Bill Yanga8aa734f3191
diff --git a/docs/content/docs/api/channel-performance.mdx b/docs/content/docs/api/channel-performance.mdxnew file mode 100644index 000000000..4661de96e--- /dev/null+++ b/docs/content/docs/api/channel-performance.mdx@@ -0,0 +1,183 @@+---+title: Compare Channel Performance+description: Rank your acquisition channels by how well they convert β not just how much traffic they send β by combining the metric, overview, and goals endpoints with channel filters.+---++import { Callout } from 'fumadocs-ui/components/callout';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';+import { Step, Steps } from 'fumadocs-ui/components/steps';++The channel that sends the most visitors is rarely the channel that sends the most *customers*. This guide ranks each acquisition channel by conversion rate so you can see which sources punch above their weight β and which ones are vanity traffic.++**Endpoints used:**++- [`GET /metric`](/docs/api/overview/metric) β sessions broken down by channel+- [`GET /goals`](/docs/api/goals/list) β conversion metrics, scoped with a channel filter++<Callout type="info">+The key technique here is the [`filters` parameter](/docs/api/getting-started#filter-parameters). Almost every endpoint accepts it, so you can take any site-wide metric and recompute it for a single segment β here, one channel at a time.+</Callout>++## The workflow++<Steps>+<Step>+**List your channels** and their session counts with `metric?parameter=channel`.+</Step>+<Step>+**For each channel, fetch your goal's conversion rate** by calling `/goals` with a `channel` filter applied.+</Step>+<Step>+**Rank by conversion rate** to reveal which channels actually drive outcomes.+</Step>+</Steps>++## Full script++This script ranks every channel by the conversion rate of a chosen goal (here, goal `1` β your signup goal). Swap in whichever goal matters to your business.++<Tabs items={['JavaScript', 'Python']}>+<Tab value="JavaScript">+```javascript title="channel-performance.js"+const API = 'https://app.rybbit.io';+const SITE = '123';+const API_KEY = process.env.RYBBIT_API_KEY;+const PRIMARY_GOAL_ID = 1; // the goal you care about++const range = { start_date: '2024-01-01', end_date: '2024-01-31', time_zone: 'America/New_York' };++async function get(path, params) {+ const url = new URL(`${API}/api/sites/${SITE}${path}`);+ Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));+ const res = await fetch(url, { headers: { Authorization: `Bearer ${API_KEY}` } });+ if (!res.ok) throw new Error(`${path} failed: ${res.status}`);+ return res.json();+}++// 1. All channels with their session counts+async function getChannels() {+ const { data } = await get('/metric', { parameter: 'channel', limit: 20, ...range });+ return data.data; // [{ value: 'Organic Search', count: 5400, ... }]+}++// 2. Conversion rate for one channel, scoped with a filter+async function goalForChannel(channel) {+ const filters = JSON.stringify([{ parameter: 'channel', type: 'equals', value: [channel] }]);+ const { data } = await get('/goals', { filters, ...range });+ return data.find((g) => g.goalId === PRIMARY_GOAL_ID);+}++async function rankChannels() {+ const channels = await getChannels();++ const rows = await Promise.all(+ channels.map(async (c) => {+ const goal = await goalForChannel(c.value);+ return {+ channel: c.value || 'Direct',+ sessions: c.count,+ conversions: goal?.total_conversions ?? 0,+ // conversion_rate comes back as a 0β1 fraction+ conversionRate: (goal?.conversion_rate ?? 0) * 100,+ };+ })+ );++ return rows.sort((a, b) => b.conversionRate - a.conversionRate);+}++rankChannels().then((rows) => {+ console.log('Channel'.padEnd(18), 'Sessions'.padStart(10), 'Conv.'.padStart(8), 'Rate'.padStart(8));+ for (const r of rows) {+ console.log(+ r.channel.padEnd(18),+ r.sessions.toLocaleString().padStart(10),+ String(r.conversions).padStart(8),+ `${r.conversionRate.toFixed(2)}%`.padStart(8)+ );+ }+});+```+</Tab>+<Tab value="Python">+```python title="channel_performance.py"+import os, json, requests++API = "https://app.rybbit.io"+SITE = "123"+API_KEY = os.environ["RYBBIT_API_KEY"]+PRIMARY_GOAL_ID = 1 # the goal you care about++RANGE = {"start_date": "2024-01-01", "end_date": "2024-01-31", "time_zone": "America/New_York"}++session = requests.Session()+session.headers["Authorization"] = f"Bearer {API_KEY}"+++def get(path, **params):+ res = session.get(f"{API}/api/sites/{SITE}{path}", params=params)+ res.raise_for_status()+ return res.json()+++def get_channels():+ # 1. All channels with their session counts+ return get("/metric", parameter="channel", limit=20, **RANGE)["data"]["data"]+++def goal_for_channel(channel):+ # 2. Conversion rate for one channel, scoped with a filter+ filters = json.dumps([{"parameter": "channel", "type": "equals", "value": [channel]}])+ goals = get("/goals", filters=filters, **RANGE)["data"]+ return next((g for g in goals if g["goalId"] == PRIMARY_GOAL_ID), None)+++def rank_channels():+ rows = []+ for c in get_channels():+ goal = goal_for_channel(c["value"])+ rows.append({+ "channel": c["value"] or "Direct",+ "sessions": c["count"],+ "conversions": goal["total_conversions"] if goal else 0,+ # conversion_rate comes back as a 0β1 fraction+ "conversion_rate": (goal["conversion_rate"] if goal else 0) * 100,+ })+ return sorted(rows, key=lambda r: r["conversion_rate"], reverse=True)+++print(f"{'Channel':<18}{'Sessions':>10}{'Conv.':>8}{'Rate':>8}")+for r in rank_channels():+ print(f"{r['channel']:<18}{r['sessions']:>10,}{r['conversions']:>8}{r['conversion_rate']:>7.2f}%")+```+</Tab>+</Tabs>++## Reading the result++```text+Channel Sessions Conv. Rate+Referral 1,820 310 17.03%+Organic Search 5,400 642 11.89%+Direct 4,220 451 10.69%+Email 980 88 8.98%+Paid Search 2,310 142 6.15%+Social 6,150 119 1.93%+```++Social sends the **most** traffic (6,150 sessions) but converts the **worst** (1.93%). Referral sends a fraction of the volume but converts nine times better. The takeaway writes itself: the referral partnerships deserve more investment, and the social strategy needs a hard look before more budget goes into it.++<Callout type="warn">+Conversion rate alone can mislead on tiny samples β Email looks healthy at 9% but it's only 88 conversions. Always show the raw `sessions` and `conversions` columns next to the rate so a channel with 12 sessions and one fluke conversion doesn't top your list.+</Callout>++## Variations++- **By UTM campaign instead of channel:** swap `parameter: 'channel'` for `parameter: 'utm_campaign'`, and filter on `utm_campaign` in the goals call. Same code, campaign-level granularity.+- **Engagement instead of conversion:** call [`/overview`](/docs/api/overview/overview) with the channel filter to compare `bounce_rate` and `session_duration` per channel β useful when you don't have a goal defined yet.+- **Full-funnel by channel:** run [`/funnels/analyze`](/docs/api/funnels/analyze) with a channel filter to see *where* in the funnel each channel's visitors fall out, not just the final rate.++## Next steps++- [Find Where Users Drop Off](/docs/api/funnel-dropoff) β once you know your best channels, fix the funnel they pour into.+- [Automated Weekly Report](/docs/api/weekly-report) β add a channel league table to a scheduled digest.diff --git a/docs/content/docs/api/funnel-dropoff.mdx b/docs/content/docs/api/funnel-dropoff.mdxnew file mode 100644index 000000000..bc9815b02--- /dev/null+++ b/docs/content/docs/api/funnel-dropoff.mdx@@ -0,0 +1,232 @@+---+title: Find Where Users Drop Off+description: Chain the funnel analysis and journeys endpoints to locate the biggest leak in a conversion flow, then discover where the users who abandon actually go instead.+---++import { Callout } from 'fumadocs-ui/components/callout';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';+import { Step, Steps } from 'fumadocs-ui/components/steps';++A funnel tells you *how many* people fall out at each step. The journeys endpoint tells you *where they went instead*. Putting them together turns "our signup funnel leaks at the pricing page" into "people leave the pricing page for the FAQ β they have unanswered questions."++**Endpoints used:**++- [`POST /funnels/analyze`](/docs/api/funnels/analyze) β step-by-step conversion and drop-off rates+- [`GET /journeys`](/docs/api/insights/journeys) β the most common navigation paths++## The workflow++<Steps>+<Step>+**Analyze the funnel** to get a drop-off rate for every step.+</Step>+<Step>+**Find the worst step** β the one with the highest `dropoff_rate`.+</Step>+<Step>+**Pull journeys that start at that step's page** using `stepFilters`, so you can see the most common next page for people who were there.+</Step>+</Steps>++## Step 1 β Analyze the funnel++Define the path a converting user should take and post it to the analyze endpoint.++<Tabs items={['JavaScript', 'Python']}>+<Tab value="JavaScript">+```javascript title="Analyze the funnel"+const API = 'https://app.rybbit.io';+const SITE = '123';+const API_KEY = process.env.RYBBIT_API_KEY;++const range = { start_date: '2024-01-01', end_date: '2024-01-31', time_zone: 'America/New_York' };++const funnelSteps = [+ { type: 'page', value: '/', name: 'Homepage' },+ { type: 'page', value: '/pricing', name: 'Pricing' },+ { type: 'page', value: '/signup', name: 'Signup' },+ { type: 'event', value: 'signup_complete', name: 'Complete' },+];++async function analyzeFunnel() {+ const url = new URL(`${API}/api/sites/${SITE}/funnels/analyze`);+ Object.entries(range).forEach(([k, v]) => url.searchParams.set(k, v));++ const res = await fetch(url, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${API_KEY}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ steps: funnelSteps }),+ });+ const { data } = await res.json();+ return data; // array of { step_number, step_name, visitors, conversion_rate, dropoff_rate }+}+```+</Tab>+<Tab value="Python">+```python title="Analyze the funnel"+import os, requests++API = "https://app.rybbit.io"+SITE = "123"+API_KEY = os.environ["RYBBIT_API_KEY"]++RANGE = {"start_date": "2024-01-01", "end_date": "2024-01-31", "time_zone": "America/New_York"}++FUNNEL_STEPS = [+ {"type": "page", "value": "/", "name": "Homepage"},+ {"type": "page", "value": "/pricing", "name": "Pricing"},+ {"type": "page", "value": "/signup", "name": "Signup"},+ {"type": "event", "value": "signup_complete", "name": "Complete"},+]+++def analyze_funnel():+ res = requests.post(+ f"{API}/api/sites/{SITE}/funnels/analyze",+ params=RANGE,+ json={"steps": FUNNEL_STEPS},+ headers={"Authorization": f"Bearer {API_KEY}"},+ )+ res.raise_for_status()+ return res.json()["data"] # list of step results+```+</Tab>+</Tabs>++A response looks like this β note that `dropoff_rate` is the percentage who left **between the previous step and this one**:++```json+{+ "data": [+ { "step_number": 1, "step_name": "Homepage", "visitors": 10000, "conversion_rate": 100, "dropoff_rate": 0 },+ { "step_number": 2, "step_name": "Pricing", "visitors": 4500, "conversion_rate": 45, "dropoff_rate": 55 },+ { "step_number": 3, "step_name": "Signup", "visitors": 1800, "conversion_rate": 18, "dropoff_rate": 60 },+ { "step_number": 4, "step_name": "Complete", "visitors": 1080, "conversion_rate": 10.8, "dropoff_rate": 40 }+ ]+}+```++## Step 2 β Find the worst step++The leak isn't always the step with the fewest visitors β it's the step with the steepest **drop-off**. Pick the maximum `dropoff_rate`.++<Tabs items={['JavaScript', 'Python']}>+<Tab value="JavaScript">+```javascript title="Find the biggest leak"+function biggestLeak(steps) {+ // Skip step 1 β it always has 0% drop-off+ return steps+ .filter((s) => s.step_number > 1)+ .reduce((worst, s) => (s.dropoff_rate > worst.dropoff_rate ? s : worst));+}++const steps = await analyzeFunnel();+const leak = biggestLeak(steps);+const enteredStep = steps[leak.step_number - 2]; // the step they were on before leaving++console.log(+ `Worst leak: ${leak.dropoff_rate}% of users left after "${enteredStep.step_name}" ` ++ `instead of reaching "${leak.step_name}".`+);+```+</Tab>+<Tab value="Python">+```python title="Find the biggest leak"+def biggest_leak(steps):+ # Skip step 1 β it always has 0% drop-off+ return max((s for s in steps if s["step_number"] > 1), key=lambda s: s["dropoff_rate"])+++steps = analyze_funnel()+leak = biggest_leak(steps)+entered_step = steps[leak["step_number"] - 2] # the step they were on before leaving++print(+ f'Worst leak: {leak["dropoff_rate"]}% of users left after "{entered_step["step_name"]}" '+ f'instead of reaching "{leak["step_name"]}".'+)+```+</Tab>+</Tabs>++In the example above, the steepest drop-off is **60%, between Pricing and Signup** β of the 4,500 people who reached the pricing page, only 1,800 went on to signup. That makes the **pricing page** the one to investigate: it's where the audience was sitting right before the biggest leak.++## Step 3 β See where the leavers went++The [journeys endpoint](/docs/api/insights/journeys) ranks the most common page paths. Use `stepFilters` to anchor step `0` to the page people were dropping from β now every returned journey shows you a common *next* page for that audience.++<Tabs items={['JavaScript', 'Python']}>+<Tab value="JavaScript">+```javascript title="What did they do after the leaky page?"+async function journeysFrom(page) {+ const stepFilters = JSON.stringify({ '0': page });+ const url = new URL(`${API}/api/sites/${SITE}/journeys`);+ url.searchParams.set('steps', '2');+ url.searchParams.set('limit', '10');+ url.searchParams.set('stepFilters', stepFilters);+ Object.entries(range).forEach(([k, v]) => url.searchParams.set(k, v));++ const res = await fetch(url, { headers: { Authorization: `Bearer ${API_KEY}` } });+ const { journeys } = await res.json();+ return journeys;+}++// The leaky step's page β '/pricing' in our example+const leakyPage = funnelSteps[leak.step_number - 2].value;+const journeys = await journeysFrom(leakyPage);++console.log(`Where users go after ${leakyPage}:`);+journeys+ .filter((j) => j.path[1] && j.path[1] !== '/signup') // exclude the intended next step+ .slice(0, 5)+ .forEach((j) => console.log(` β ${j.path[1]} (${j.count} sessions, ${j.percentage}%)`));+```+</Tab>+<Tab value="Python">+```python title="What did they do after the leaky page?"+import json+++def journeys_from(page):+ res = requests.get(+ f"{API}/api/sites/{SITE}/journeys",+ params={"steps": 2, "limit": 10, "stepFilters": json.dumps({"0": page}), **RANGE},+ headers={"Authorization": f"Bearer {API_KEY}"},+ )+ res.raise_for_status()+ return res.json()["journeys"]+++# The leaky step's page β '/pricing' in our example+leaky_page = FUNNEL_STEPS[leak["step_number"] - 2]["value"]+journeys = journeys_from(leaky_page)++print(f"Where users go after {leaky_page}:")+for j in [j for j in journeys if len(j["path"]) > 1 and j["path"][1] != "/signup"][:5]:+ print(f' β {j["path"][1]} ({j["count"]} sessions, {j["percentage"]}%)')+```+</Tab>+</Tabs>++### The insight++```text+Where users go after /pricing:+ β /faq (1,240 sessions, 27.6%)+ β / (820 sessions, 18.2%)+ β /enterprise (610 sessions, 13.6%)+```++More than a quarter of people who hit Pricing and didn't sign up went to the FAQ β a strong signal that pricing raises questions your FAQ has to answer. That's a far more actionable finding than "the pricing page has a 60% drop-off."++<Callout type="info">+**Quantify before you act.** Combine the funnel and journey numbers into a one-line business case: *"2,700 users/month leave Pricing; 28% head to the FAQ. Surfacing the top FAQ answers on the pricing page could recover a meaningful share of them."*+</Callout>++## Next steps++- [Compare Marketing Channel Performance](/docs/api/channel-performance) β find out which traffic sources fill the top of this funnel with people who actually convert.+- [Funnels API reference](/docs/api/funnels/analyze) β event steps, property matching, and per-step session lookups.diff --git a/docs/content/docs/api/getting-started.mdx b/docs/content/docs/api/getting-started.mdxindex fda3f1ad6..37e19a863 100644--- a/docs/content/docs/api/getting-started.mdx+++ b/docs/content/docs/api/getting-started.mdx@@ -24,6 +24,16 @@ The playground provides:This is the recommended way to familiarize yourself with the API before integrating it into your applications.+## Guides++Looking for what to *build* with the API? These end-to-end recipes chain endpoints together to solve a real problem:++- [**Automated Weekly Report**](/docs/api/weekly-report) β a scheduled digest of last week's traffic, week-over-week change, and top pages and sources.+- [**Find Where Users Drop Off**](/docs/api/funnel-dropoff) β locate the biggest leak in a funnel, then see where the people who abandon go instead.+- [**Compare Channel Performance**](/docs/api/channel-performance) β rank acquisition channels by how well they convert, not just how much traffic they send.+- [**Build a Live Visitor Feed**](/docs/api/live-feed) β poll the events endpoint for a real-time activity stream you can render or alert on.+- [**Export Events to a Warehouse**](/docs/api/export-events) β backfill your full event history and keep it in sync with an incremental job.+## AuthenticationAll API requests must include authentication using one of the following methods:diff --git a/docs/content/docs/api/live-feed.mdx b/docs/content/docs/api/live-feed.mdxnew file mode 100644index 000000000..7b0bcf7f8--- /dev/null+++ b/docs/content/docs/api/live-feed.mdx@@ -0,0 +1,193 @@+---+title: Build a Live Visitor Feed+description: Poll the live visitor count and the events endpoint to build a real-time activity stream β the foundation for a live dashboard, an internal "who's online" widget, or an alert when a key page gets traffic.+---++import { Callout } from 'fumadocs-ui/components/callout';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';+import { Step, Steps } from 'fumadocs-ui/components/steps';++Rybbit doesn't push a websocket stream, but the events endpoint is built for polling: pass a `since_timestamp` and you get only the events that happened after it. This guide builds a self-advancing feed loop you can wire into a dashboard, a terminal ticker, or an alerting rule.++**Endpoints used:**++- [`GET /live-user-count`](/docs/api/overview/live-visitors) β how many visitors are active right now+- [`GET /events`](/docs/api/events/list) β the event stream, polled incrementally++## How incremental polling works++The events endpoint returns the newest events first. To stream without duplicates, remember the timestamp of the most recent event you've seen and send it as `since_timestamp` on the next request β the API returns only events newer than that, up to 500 per call.++<Steps>+<Step>+**Fetch the initial batch** to establish a starting watermark (the newest timestamp).+</Step>+<Step>+**On an interval, request events `since_timestamp`** = your watermark.+</Step>+<Step>+**Process the new events** (print, render, alert) and advance the watermark to the newest one returned.+</Step>+</Steps>++<Callout type="info">+`since_timestamp` returns up to **500** events per call. If you expect more than 500 events between polls (a very high-traffic site with a long interval), poll more frequently so each batch stays under the cap.+</Callout>++## Full script++A Node script that prints a live count plus a rolling feed of activity. The same loop drives a browser dashboard β just replace `console.log` with DOM updates.++<Tabs items={['JavaScript', 'Python']}>+<Tab value="JavaScript">+```javascript title="live-feed.js"+const API = 'https://app.rybbit.io';+const SITE = '123';+const API_KEY = process.env.RYBBIT_API_KEY;+const POLL_MS = 10000; // every 10 seconds++async function get(path, params = {}) {+ const url = new URL(`${API}/api/sites/${SITE}${path}`);+ Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));+ const res = await fetch(url, { headers: { Authorization: `Bearer ${API_KEY}` } });+ if (!res.ok) throw new Error(`${path} failed: ${res.status}`);+ return res.json();+}++async function liveCount() {+ const { count } = await get('/live-user-count', { minutes: 5 });+ return count;+}++function describe(e) {+ const where = e.city ? `${e.city}, ${e.country}` : e.country || 'Unknown';+ if (e.type === 'pageview') return `π viewed ${e.pathname} β ${where}`;+ if (e.type === 'custom_event') return `β‘ ${e.event_name} (${e.pathname}) β ${where}`;+ if (e.type === 'outbound') return `βοΈ left via ${e.pathname} β ${where}`;+ return `β’ ${e.type} β ${where}`;+}++let watermark = null; // ISO timestamp of the newest event we've shown++async function poll() {+ try {+ const params = watermark ? { since_timestamp: watermark } : { page_size: 20 };+ const [{ data: events }, count] = await Promise.all([get('/events', params), liveCount()]);++ // Events come back newest-first; show oldest-first so the feed reads top-to-bottom+ for (const e of [...events].reverse()) {+ console.log(`[${new Date(e.timestamp).toLocaleTimeString()}] ${describe(e)}`);+ }+ if (events.length) watermark = events[0].timestamp; // newest event becomes the new watermark++ process.stdout.write(`\nπ’ ${count} visitors online\n`);+ } catch (err) {+ console.error('poll error:', err.message);+ }+}++console.log('Starting live feedβ¦ (Ctrl+C to stop)');+poll();+setInterval(poll, POLL_MS);+```+</Tab>+<Tab value="Python">+```python title="live_feed.py"+import os, time+from datetime import datetime+import requests++API = "https://app.rybbit.io"+SITE = "123"+API_KEY = os.environ["RYBBIT_API_KEY"]+POLL_SECONDS = 10++session = requests.Session()+session.headers["Authorization"] = f"Bearer {API_KEY}"+++def get(path, **params):+ res = session.get(f"{API}/api/sites/{SITE}{path}", params=params)+ res.raise_for_status()+ return res.json()+++def live_count():+ return get("/live-user-count", minutes=5)["count"]+++def describe(e):+ where = f'{e["city"]}, {e["country"]}' if e.get("city") else e.get("country") or "Unknown"+ if e["type"] == "pageview":+ return f'π viewed {e["pathname"]} β {where}'+ if e["type"] == "custom_event":+ return f'β‘ {e["event_name"]} ({e["pathname"]}) β {where}'+ if e["type"] == "outbound":+ return f'βοΈ left via {e["pathname"]} β {where}'+ return f'β’ {e["type"]} β {where}'+++watermark = None # ISO timestamp of the newest event we've shown++print("Starting live feedβ¦ (Ctrl+C to stop)")+while True:+ try:+ params = {"since_timestamp": watermark} if watermark else {"page_size": 20}+ events = get("/events", **params)["data"]++ # Events come back newest-first; show oldest-first so the feed reads top-to-bottom+ for e in reversed(events):+ ts = datetime.fromisoformat(e["timestamp"].replace("Z", "+00:00")).strftime("%H:%M:%S")+ print(f"[{ts}] {describe(e)}")+ if events:+ watermark = events[0]["timestamp"] # newest event becomes the new watermark++ print(f"\nπ’ {live_count()} visitors online\n")+ except Exception as err:+ print(f"poll error: {err}")+ time.sleep(POLL_SECONDS)+```+</Tab>+</Tabs>++## Example output++```text+Starting live feedβ¦ (Ctrl+C to stop)+[14:22:01] π viewed /pricing β San Francisco, US+[14:22:03] β‘ signup (/signup) β London, GB+[14:22:05] βοΈ left via /docs β Berlin, DE++π’ 42 visitors online+```++## Turn it into an alert++Because each poll hands you the raw events, you can act on them instead of just printing. For example, ping a channel whenever someone hits your enterprise pricing page:++<Tabs items={['JavaScript']}>+<Tab value="JavaScript">+```javascript title="React to specific events"+for (const e of events) {+ if (e.type === 'pageview' && e.pathname === '/enterprise') {+ await fetch(process.env.SLACK_WEBHOOK, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ text: `π’ Enterprise page visit from ${e.city || e.country} (${e.referrer || 'direct'})`,+ }),+ });+ }+}+```+</Tab>+</Tabs>++<Callout type="warn">+**Mind the rate limits.** On Rybbit Cloud, API keys are capped per minute by plan (see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only)). A 10-second poll is 6 requests/minute β well within the Standard tier. If you add the live-count call, that's 12/minute. Lengthen the interval or drop the count call if you're close to your limit. Self-hosted instances have no limit.+</Callout>++## Next steps++- [Events API reference](/docs/api/events/list) β full event object fields, plus `before_timestamp` for scrolling backwards through history.+- [Export Raw Events to Your Warehouse](/docs/api/export-events) β the same `since_timestamp` mechanism, used for durable incremental syncs instead of a live view.diff --git a/docs/content/docs/api/meta.json b/docs/content/docs/api/meta.jsonindex b91715656..7c584a230 100644--- a/docs/content/docs/api/meta.json+++ b/docs/content/docs/api/meta.json@@ -5,6 +5,11 @@"root": true,"pages": ["getting-started",+ "---Guides---",+ "weekly-report",+ "funnel-dropoff",+ "channel-performance",+ "live-feed","---Endpoints---","sending-events","overview",diff --git a/docs/content/docs/api/weekly-report.mdx b/docs/content/docs/api/weekly-report.mdxnew file mode 100644index 000000000..73cf3e761--- /dev/null+++ b/docs/content/docs/api/weekly-report.mdx@@ -0,0 +1,265 @@+---+title: Automated Weekly Report+description: Combine the overview and metric endpoints into a scheduled digest that summarizes last week's traffic, the week-over-week change, and your top pages and traffic sources.+---++import { Callout } from 'fumadocs-ui/components/callout';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';+import { Step, Steps } from 'fumadocs-ui/components/steps';++This guide builds a script you can run on a schedule (a cron job, GitHub Action, or serverless function) that pulls last week's numbers, compares them to the week before, and posts a digest to Slack, email, or anywhere else.++**Endpoints used:**++- [`GET /overview`](/docs/api/overview/overview) β headline metrics for a date range+- [`GET /metric`](/docs/api/overview/metric) β top pages and traffic sources++<Callout type="info">+Every analytics endpoint takes the same [time parameters](/docs/api/getting-started#time-parameters). The trick behind any comparison report is simply calling the same endpoint twice with two adjacent date ranges.+</Callout>++## The workflow++<Steps>+<Step>+**Fetch this week's overview** for the last 7 days.+</Step>+<Step>+**Fetch last week's overview** for the 7 days before that, so you can compute the change.+</Step>+<Step>+**Fetch top pages and top sources** from the `metric` endpoint to add context.+</Step>+<Step>+**Format and deliver** the digest.+</Step>+</Steps>++## Full script++This example posts a formatted message to a Slack incoming webhook, but the `buildReport` function returns plain data you can route anywhere.++<Tabs items={['JavaScript', 'Python']}>+<Tab value="JavaScript">+```javascript title="weekly-report.js"+const API = 'https://app.rybbit.io';+const SITE = '123';+const API_KEY = process.env.RYBBIT_API_KEY;+const SLACK_WEBHOOK = process.env.SLACK_WEBHOOK;+const TZ = 'America/New_York';++// Helper: format a Date as YYYY-MM-DD+const ymd = (d) => d.toISOString().slice(0, 10);++async function get(path, params) {+ const url = new URL(`${API}/api/sites/${SITE}${path}`);+ Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));+ const res = await fetch(url, {+ headers: { Authorization: `Bearer ${API_KEY}` },+ });+ if (!res.ok) throw new Error(`${path} failed: ${res.status}`);+ return res.json();+}++async function overview(start, end) {+ const { data } = await get('/overview', {+ start_date: ymd(start),+ end_date: ymd(end),+ time_zone: TZ,+ });+ return data;+}++async function topMetric(parameter, start, end, limit = 5) {+ const { data } = await get('/metric', {+ parameter,+ start_date: ymd(start),+ end_date: ymd(end),+ time_zone: TZ,+ limit,+ });+ return data.data; // metric nests results under data.data+}++function pctChange(current, previous) {+ if (!previous) return null;+ return ((current - previous) / previous) * 100;+}++async function buildReport() {+ const now = new Date();+ const thisWeekStart = new Date(now); thisWeekStart.setDate(now.getDate() - 7);+ const lastWeekEnd = new Date(now); lastWeekEnd.setDate(now.getDate() - 8);+ const lastWeekStart = new Date(now); lastWeekStart.setDate(now.getDate() - 14);++ const [thisWeek, lastWeek, topPages, topSources] = await Promise.all([+ overview(thisWeekStart, now),+ overview(lastWeekStart, lastWeekEnd),+ topMetric('pathname', thisWeekStart, now),+ topMetric('referrer', thisWeekStart, now),+ ]);++ return {+ sessions: { value: thisWeek.sessions, change: pctChange(thisWeek.sessions, lastWeek.sessions) },+ users: { value: thisWeek.users, change: pctChange(thisWeek.users, lastWeek.users) },+ pageviews:{ value: thisWeek.pageviews, change: pctChange(thisWeek.pageviews, lastWeek.pageviews) },+ bounceRate: thisWeek.bounce_rate,+ topPages,+ topSources,+ };+}++function arrow(change) {+ if (change === null) return '';+ const sign = change >= 0 ? 'β²' : 'βΌ';+ return ` ${sign} ${Math.abs(change).toFixed(1)}%`;+}++async function postToSlack(r) {+ const lines = [+ `*π Weekly Analytics Report*`,+ ``,+ `β’ Sessions: *${r.sessions.value.toLocaleString()}*${arrow(r.sessions.change)}`,+ `β’ Unique users: *${r.users.value.toLocaleString()}*${arrow(r.users.change)}`,+ `β’ Pageviews: *${r.pageviews.value.toLocaleString()}*${arrow(r.pageviews.change)}`,+ `β’ Bounce rate: *${r.bounceRate.toFixed(1)}%*`,+ ``,+ `*Top pages*`,+ ...r.topPages.map((p) => ` ${p.value} β ${p.count.toLocaleString()}`),+ ``,+ `*Top sources*`,+ ...r.topSources.map((s) => ` ${s.value || 'Direct'} β ${s.count.toLocaleString()}`),+ ];+ await fetch(SLACK_WEBHOOK, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ text: lines.join('\n') }),+ });+}++buildReport().then(postToSlack).catch(console.error);+```+</Tab>+<Tab value="Python">+```python title="weekly_report.py"+import os+from datetime import datetime, timedelta+import requests++API = "https://app.rybbit.io"+SITE = "123"+API_KEY = os.environ["RYBBIT_API_KEY"]+SLACK_WEBHOOK = os.environ["SLACK_WEBHOOK"]+TZ = "America/New_York"++session = requests.Session()+session.headers["Authorization"] = f"Bearer {API_KEY}"+++def ymd(d: datetime) -> str:+ return d.strftime("%Y-%m-%d")+++def get(path: str, **params):+ res = session.get(f"{API}/api/sites/{SITE}{path}", params=params)+ res.raise_for_status()+ return res.json()+++def overview(start, end):+ return get("/overview", start_date=ymd(start), end_date=ymd(end), time_zone=TZ)["data"]+++def top_metric(parameter, start, end, limit=5):+ # metric nests results under data.data+ return get("/metric", parameter=parameter, start_date=ymd(start),+ end_date=ymd(end), time_zone=TZ, limit=limit)["data"]["data"]+++def pct_change(current, previous):+ return None if not previous else (current - previous) / previous * 100+++def build_report():+ now = datetime.utcnow()+ this_start = now - timedelta(days=7)+ last_end = now - timedelta(days=8)+ last_start = now - timedelta(days=14)++ this_week = overview(this_start, now)+ last_week = overview(last_start, last_end)++ return {+ "sessions": (this_week["sessions"], pct_change(this_week["sessions"], last_week["sessions"])),+ "users": (this_week["users"], pct_change(this_week["users"], last_week["users"])),+ "pageviews": (this_week["pageviews"], pct_change(this_week["pageviews"], last_week["pageviews"])),+ "bounce_rate": this_week["bounce_rate"],+ "top_pages": top_metric("pathname", this_start, now),+ "top_sources": top_metric("referrer", this_start, now),+ }+++def arrow(change):+ if change is None:+ return ""+ return f" {'β²' if change >= 0 else 'βΌ'} {abs(change):.1f}%"+++def post_to_slack(r):+ lines = [+ "*π Weekly Analytics Report*", "",+ f"β’ Sessions: *{r['sessions'][0]:,}*{arrow(r['sessions'][1])}",+ f"β’ Unique users: *{r['users'][0]:,}*{arrow(r['users'][1])}",+ f"β’ Pageviews: *{r['pageviews'][0]:,}*{arrow(r['pageviews'][1])}",+ f"β’ Bounce rate: *{r['bounce_rate']:.1f}%*", "",+ "*Top pages*",+ *[f" {p['value']} β {p['count']:,}" for p in r["top_pages"]], "",+ "*Top sources*",+ *[f" {s['value'] or 'Direct'} β {s['count']:,}" for s in r["top_sources"]],+ ]+ requests.post(SLACK_WEBHOOK, json={"text": "\n".join(lines)})+++post_to_slack(build_report())+```+</Tab>+</Tabs>++## Example output++```text+π Weekly Analytics Report++β’ Sessions: 15,420 β² 12.3%+β’ Unique users: 12,847 β² 9.8%+β’ Pageviews: 48,933 βΌ 2.1%+β’ Bounce rate: 42.8%++Top pages+ / β 8,230+ /pricing β 3,120+ /blog/getting-started β 1,940++Top sources+ google.com β 6,410+ Direct β 4,220+ twitter.com β 1,180+```++## Schedule it++Run the script every Monday morning with cron:++```bash title="crontab -e"+# Every Monday at 9:00 AM+0 9 * * 1 RYBBIT_API_KEY=xxx SLACK_WEBHOOK=https://hooks.slack.com/... node /path/to/weekly-report.js+```++<Callout type="info">+**Want a richer report?** The same pattern extends naturally. Add `topMetric('channel', ...)` for marketing channels, `topMetric('country', ...)` for geography, or call the [`time-series` endpoint](/docs/api/overview/time-series) with `bucket=day` to attach a 7-point trend line.+</Callout>++## Next steps++- [Compare Marketing Channel Performance](/docs/api/channel-performance) β go beyond traffic counts and rank sources by how well they convert.+- [Export Raw Events to Your Warehouse](/docs/api/export-events) β if you'd rather build reports in your own BI tool.