Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(api): public metrics API v1 under /api/v1 with docs (#422)
Gökhan Geyik50f348788f00
diff --git a/docs/api-reference/authentication.mdx b/docs/api-reference/authentication.mdxindex 4c4a1400b..0b9a69131 100644--- a/docs/api-reference/authentication.mdx+++ b/docs/api-reference/authentication.mdx@@ -3,6 +3,17 @@ title: "Authentication"description: "How to authenticate API requests to the Ansvisor server."---+## API keys (Public Metrics API)++The versioned `/api/v1/*` endpoints on the **web app** authenticate with long-lived Ansvisor API keys (prefix `ans_`), created under **Settings → API Keys** in the dashboard:++```bash+curl "https://app.ansvisor.com/api/v1/brands" \+ -H "Authorization: Bearer ans_..."+```++This is the right choice for external integrations — Looker Studio, Sheets, scripts, and the [MCP server](/guides/mcp-server). See the [Metrics API reference](/api-reference/metrics) for the endpoint list.+## Bearer tokenAll `/api/*` endpoints on the Ansvisor server require a Supabase JWT bearer token in the `Authorization` header:@@ -17,10 +28,12 @@ curl https://api.your-domain.com/api/health \The cleanest way is via the Supabase JS client in your own backend code:```ts-import { createClient } from '@supabase/supabase-js';+import { createClient } from "@supabase/supabase-js";const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);-const { data: { session } } = await supabase.auth.signInWithPassword({+const {+ data: { session },+} = await supabase.auth.signInWithPassword({email,password,});@@ -50,9 +63,15 @@ Three endpoints don't require any auth:- `GET /healthz` (where exposed) — basic uptime check<Note>-The internal `/api/health` endpoint described in the routes file IS auth-protected — by design, it returns the authenticated user's ID. For uptime monitoring, use `/t.js` instead (returns 200 + JS content).+ The internal `/api/health` endpoint described in the routes file IS+ auth-protected — by design, it returns the authenticated user's ID. For uptime+ monitoring, use `/t.js` instead (returns 200 + JS content).</Note>-<Card title="Continue: Brands API" icon="arrow-right" href="/api-reference/brands">+<Card+ title="Continue: Brands API"+ icon="arrow-right"+ href="/api-reference/brands"+>CRUD endpoints for managing brands programmatically.</Card>diff --git a/docs/api-reference/metrics.mdx b/docs/api-reference/metrics.mdxnew file mode 100644index 000000000..f252a62e5--- /dev/null+++ b/docs/api-reference/metrics.mdx@@ -0,0 +1,127 @@+---+title: "Metrics API"+description: "Pull AI visibility metrics into Looker Studio, Sheets, or your own dashboards with an API key."+---++The Public Metrics API is a read-only, versioned REST surface under `/api/v1/*` on the **web app** host. It exposes the same aggregates the dashboard renders — visibility KPIs, trends, share of voice, citations, AI traffic, prompt performance and shopping cards — so you can blend Ansvisor data with GA4 / Search Console in an external reporting tool.++<Note>+ These endpoints live on the web app (Next.js), not the Express API server. If+ you self-host, the base URL is your web app's domain.+</Note>++## Authentication++Every request needs an Ansvisor API key in the `Authorization` header. Create one under **Settings → API Keys** in the dashboard — the plaintext key (prefix `ans_`) is shown exactly once at creation time.++```bash+curl "https://app.ansvisor.com/api/v1/brands" \+ -H "Authorization: Bearer ans_..."+```++Keys are scoped to the user who created them and resolve to that user's organization: every endpoint only returns data for brands the organization owns. Revoking a key (Settings → API Keys) takes effect immediately.++`GET /api/v1/whoami` echoes the resolved identity — useful as a connection test:++```json+{ "userId": "…", "email": "[email protected]", "organizationId": "…" }+```++## Conventions++- All endpoints are `GET` and return JSON.+- `brand_id` is required on every metrics endpoint; list your brands via `GET /api/v1/brands` first.+- `date_from` / `date_to` accept `YYYY-MM-DD` (the `date_to` day is included through 23:59:59 UTC).+- Optional filters shared by most endpoints: `model` (comma-separated model slugs), `region`, `topic_id`.+- Errors return `{ "error": "…" }` with `400` (bad params), `401` (missing/invalid key), `404` (brand not in your organization) or `500`.++## Endpoints++### List brands++```http+GET /api/v1/brands+```++Returns `{ "brands": [{ "id", "name", "slug", "industry", "region", "created_at" }] }` for the caller's organization.++### Visibility summary++```http+GET /api/v1/visibility-summary?brand_id=<uuid>&date_from=2026-06-01&date_to=2026-06-30+```++Overall KPIs for the window: result count, average visibility score, total mentions, total citations, plus the top 5 competitors by mentions. Supports `model`, `region`.++### Visibility trend++```http+GET /api/v1/visibility-trend?brand_id=<uuid>&granularity=day+```++Time-bucketed visibility for charting — the endpoint to join against GA4 date series. `granularity` is `day` (default) or `week` (ISO Monday buckets). Supports `date_from`, `date_to`, `model`, `region`, `topic_id`. Returns:++```json+{+ "granularity": "day",+ "buckets": [+ {+ "date": "2026-06-01",+ "result_count": 24,+ "avg_visibility_score": 47,+ "total_mentions": 31,+ "total_citations": 12,+ "avg_competitor_score": 39+ }+ ]+}+```++### Competitor comparison & share of voice++```http+GET /api/v1/competitor-comparison?brand_id=<uuid>&date_from=2026-06-01&date_to=2026-06-30+```++The brand's benchmark row, one row per competitor (visibility, mentions, citations, appearances) and a `share_of_voice` block with the overall SoV percentage and a per-platform split. Supports `model`, `region`, `topic_id`.++### Citations++```http+GET /api/v1/citations?brand_id=<uuid>&source_filter=external&limit=50+```++The domains and URLs AI engines cite around the brand: totals, a source-type breakdown (owned / competitor / editorial / forum / social / review / institutional), `top_domains` and `top_urls`. `source_filter` is one of `all` (default), `owned`, `competitor`, `external`; `limit` caps the top lists (default 50, max 200). Supports `date_from`, `date_to`, `model`, `region`, `topic_id`.++### AI traffic++```http+GET /api/v1/ai-traffic?brand_id=<uuid>&date_from=2026-06-01&date_to=2026-06-30+```++Visits referred by AI platforms, collected by the tracking pixel: `total_visits`, `platform_breakdown`, `top_pages` (top 10 paths) and `country_breakdown`.++### Prompt performance++```http+GET /api/v1/prompt-performance?brand_id=<uuid>&sort_by=visibility&order=desc&limit=10+```++Per-prompt aggregates for the window: average visibility, mentions, citations, appearance count and the average competitor score per prompt. `sort_by` is `visibility` (default), `mentions`, `citations` or `appearances`; `order` is `desc` (default) or `asc`; `limit` 1–100 (default 10). Supports `date_from`, `date_to`, `model`, `region`, `topic_id`.++### Shopping cards++```http+GET /api/v1/shopping-cards?brand_id=<uuid>&role=own&limit=50+```++Normalized shopping-card rows (product title, brand, price, merchant, rating, position) captured from AI shopping surfaces. `role` filters to `own`, `competitor` or `other` matches; cursor-paginated via `limit` (default 50, max 200) and the returned `next_cursor`.++## Using it from Looker Studio++Until a native Community Connector ships, any generic JSON/API connector (or a small Apps Script that calls these endpoints with `UrlFetchApp`) works: point it at `/api/v1/visibility-trend` with your key in the `Authorization` header and join on the `date` column. The endpoints are also what a future official connector will consume.++<Card title="MCP server" icon="plug" href="/guides/mcp-server">+ The same API keys power the Ansvisor MCP server — query these metrics from+ Claude or any MCP client.+</Card>diff --git a/docs/mint.json b/docs/mint.jsonindex 0beccc8a6..e45d965b6 100644--- a/docs/mint.json+++ b/docs/mint.json@@ -100,6 +100,7 @@"group": "API Reference","pages": ["api-reference/authentication",+ "api-reference/metrics","api-reference/brands","api-reference/tracking","api-reference/webhooks"diff --git a/web/src/app/api/v1/ai-traffic/route.ts b/web/src/app/api/v1/ai-traffic/route.tsnew file mode 100644index 000000000..731e2cc0b--- /dev/null+++ b/web/src/app/api/v1/ai-traffic/route.ts@@ -0,0 +1,37 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getAiTrafficFor } from '@/lib/mcp/data';++/**+ * GET /api/v1/ai-traffic+ *+ * AI-referred traffic breakdown for the Public Metrics API — total visits+ * plus platform / top-page / country splits from the tracking pixel. Same+ * data-layer function the MCP `get_ai_traffic` tool uses, same ownership+ * guarantee. Query params: brand_id (required), date_from, date_to.+ */+export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const url = new URL(req.url);+ const brandId = url.searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }++ try {+ const result = await getAiTrafficFor(auth, {+ brandId,+ dateFrom: url.searchParams.get('date_from') ?? undefined,+ dateTo: url.searchParams.get('date_to') ?? undefined,+ });+ if (!result) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json(result);+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/app/api/v1/brands/route.ts b/web/src/app/api/v1/brands/route.tsnew file mode 100644index 000000000..2a74160cc--- /dev/null+++ b/web/src/app/api/v1/brands/route.ts@@ -0,0 +1,7 @@+/**+ * GET /api/v1/brands+ *+ * Canonical public path — see `whoami/route.ts` for the `/api/v1` ↔+ * `/api/mcp` relationship. Lists the brands in the caller's organization.+ */+export { GET } from '@/app/api/mcp/brands/route';diff --git a/web/src/app/api/v1/citations/route.ts b/web/src/app/api/v1/citations/route.tsnew file mode 100644index 000000000..0a6f3d83a--- /dev/null+++ b/web/src/app/api/v1/citations/route.ts@@ -0,0 +1,70 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import {+ listCitationsFor,+ CITATION_SOURCE_FILTERS,+ type CitationSourceFilter,+} from '@/lib/mcp/data';++/**+ * GET /api/v1/citations+ *+ * Citations overview for the Public Metrics API — the domains and URLs AI+ * engines cite alongside a brand, classified by source type. Same data-layer+ * function the MCP `list_citations` tool uses, same ownership guarantee.+ * Query params: brand_id (required), date_from, date_to, model, region,+ * topic_id, limit (1-200), source_filter (all|owned|competitor|external).+ */+export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const url = new URL(req.url);+ const brandId = url.searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }++ const sourceFilterParam = url.searchParams.get('source_filter') || undefined;+ if (+ sourceFilterParam &&+ !CITATION_SOURCE_FILTERS.includes(sourceFilterParam as CitationSourceFilter)+ ) {+ return NextResponse.json(+ { error: `source_filter must be one of: ${CITATION_SOURCE_FILTERS.join(', ')}` },+ { status: 400 },+ );+ }++ let limit: number | undefined;+ const limitParam = url.searchParams.get('limit');+ if (limitParam !== null) {+ limit = Number.parseInt(limitParam, 10);+ if (Number.isNaN(limit) || limit < 1 || limit > 200) {+ return NextResponse.json(+ { error: 'limit must be a number between 1 and 200' },+ { status: 400 },+ );+ }+ }++ try {+ const result = await listCitationsFor(auth, {+ brandId,+ dateFrom: url.searchParams.get('date_from') ?? undefined,+ dateTo: url.searchParams.get('date_to') ?? undefined,+ model: url.searchParams.get('model') ?? undefined,+ region: url.searchParams.get('region') ?? undefined,+ topicId: url.searchParams.get('topic_id') ?? undefined,+ limit,+ sourceFilter: sourceFilterParam as CitationSourceFilter | undefined,+ });+ if (!result) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json(result);+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/app/api/v1/competitor-comparison/route.ts b/web/src/app/api/v1/competitor-comparison/route.tsnew file mode 100644index 000000000..c2cbf7f3c--- /dev/null+++ b/web/src/app/api/v1/competitor-comparison/route.ts@@ -0,0 +1,8 @@+/**+ * GET /api/v1/competitor-comparison+ *+ * Canonical public path — see `whoami/route.ts` for the `/api/v1` ↔+ * `/api/mcp` relationship. Competitor benchmark + share of voice for a+ * brand and date window.+ */+export { GET } from '@/app/api/mcp/competitor-comparison/route';diff --git a/web/src/app/api/v1/prompt-performance/route.ts b/web/src/app/api/v1/prompt-performance/route.tsnew file mode 100644index 000000000..5ae2f452b--- /dev/null+++ b/web/src/app/api/v1/prompt-performance/route.ts@@ -0,0 +1,8 @@+/**+ * GET /api/v1/prompt-performance+ *+ * Canonical public path — see `whoami/route.ts` for the `/api/v1` ↔+ * `/api/mcp` relationship. Per-prompt visibility/mention/citation+ * aggregates, sortable and limitable.+ */+export { GET } from '@/app/api/mcp/prompt-performance/route';diff --git a/web/src/app/api/v1/shopping-cards/route.ts b/web/src/app/api/v1/shopping-cards/route.tsnew file mode 100644index 000000000..0e762a773--- /dev/null+++ b/web/src/app/api/v1/shopping-cards/route.ts@@ -0,0 +1,7 @@+/**+ * GET /api/v1/shopping-cards+ *+ * Canonical public path — see `whoami/route.ts` for the `/api/v1` ↔+ * `/api/mcp` relationship. Cursor-paginated normalized shopping-card rows.+ */+export { GET } from '@/app/api/mcp/shopping-cards/route';diff --git a/web/src/app/api/v1/visibility-summary/route.ts b/web/src/app/api/v1/visibility-summary/route.tsnew file mode 100644index 000000000..562e27a35--- /dev/null+++ b/web/src/app/api/v1/visibility-summary/route.ts@@ -0,0 +1,8 @@+/**+ * GET /api/v1/visibility-summary+ *+ * Canonical public path — see `whoami/route.ts` for the `/api/v1` ↔+ * `/api/mcp` relationship. Overall visibility KPIs + top competitors for a+ * brand and date window.+ */+export { GET } from '@/app/api/mcp/visibility-summary/route';diff --git a/web/src/app/api/v1/visibility-trend/route.ts b/web/src/app/api/v1/visibility-trend/route.tsnew file mode 100644index 000000000..4caad1fee--- /dev/null+++ b/web/src/app/api/v1/visibility-trend/route.ts@@ -0,0 +1,8 @@+/**+ * GET /api/v1/visibility-trend+ *+ * Canonical public path — see `whoami/route.ts` for the `/api/v1` ↔+ * `/api/mcp` relationship. Daily/weekly visibility buckets, ready to plot+ * against GA4 / Search Console time series in an external dashboard.+ */+export { GET } from '@/app/api/mcp/visibility-trend/route';diff --git a/web/src/app/api/v1/whoami/route.ts b/web/src/app/api/v1/whoami/route.tsnew file mode 100644index 000000000..28d893e61--- /dev/null+++ b/web/src/app/api/v1/whoami/route.ts@@ -0,0 +1,10 @@+/**+ * GET /api/v1/whoami+ *+ * Canonical public path for the key-introspection endpoint. `/api/v1/*` is+ * the versioned Public Metrics API surface (Looker Studio, Sheets, custom+ * dashboards); the handlers live under `/api/mcp/*` where they were first+ * built for the MCP server's parallel REST surface, and both paths serve+ * identical responses with the same `ans_` API-key auth.+ */+export { GET } from '@/app/api/mcp/whoami/route';