Skip to content

Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.

fix(supermetrics): align authentication and query resources with public APIs

Rudy Celekli325d349ae933
diff --git a/tests/clis/supermetrics-contract.test.cjs b/tests/clis/supermetrics-contract.test.cjs
new file mode 100644
index 0000000..54c32a9
--- /dev/null
+++ b/tests/clis/supermetrics-contract.test.cjs
@@ -0,0 +1,63 @@
+const { test } = require('node:test')
+const assert = require('node:assert/strict')
+const { spawnSync } = require('node:child_process')
+const path = require('node:path')
+const cli = path.resolve(__dirname, '../../tools/clis/supermetrics.js')
+function run(args, network = true, status = 200) {
+ const source = `global.fetch=async(url,options)=>{
+ if(!${network}) throw new Error('Unexpected network request');
+ return {ok:${status}<400,status:${status},text:async()=>JSON.stringify({url,method:options.method,headers:options.headers,body:options.body?JSON.parse(options.body):null})};
+ }; process.argv=['node',${JSON.stringify(cli)},...${JSON.stringify(args)}];require(${JSON.stringify(cli)});`
+ return spawnSync(process.execPath,['-e',source],{encoding:'utf8',timeout:5000,
+ env:{...process.env,SUPERMETRICS_API_KEY:'fixture-key'}})
+}
+function output(r) { assert.equal(r.status,0,r.stderr);return JSON.parse(r.stdout) }
+const query=['query','--ds-id','GA4','--ds-accounts','123,456','--date-range','last_month','--fields','sessions, date']
+test('query uses supported Bearer authentication and field IDs',()=>{
+ const r=output(run(query));assert.equal(r.headers.Authorization,'Bearer fixture-key')
+ assert.equal(Object.hasOwn(r.headers,'x-api-key'),false)
+ assert.equal(r.url,'https://api.supermetrics.com/query/data/json')
+ assert.deepEqual(r.body.fields,[{id:'sessions'},{id:'date'}])
+ assert.equal(r.body.ds_accounts,'123,456');assert.equal(r.body.date_range_type,'last_month')
+})
+test('query custom range retains exact dates and filters',()=>{
+ const r=output(run([...query.slice(0,5),'--date-range','custom','--fields','date','--start-date','2026-09-01','--end-date','2026-09-20','--filter','sessions > 10','--max-rows','25']))
+ assert.equal(r.body.start_date,'2026-09-01');assert.equal(r.body.end_date,'2026-09-20')
+ assert.equal(r.body.filter,'sessions > 10');assert.equal(r.body.max_rows,25)
+})
+test('last_28_days shorthand resolves to documented relative date strings',()=>{
+ const r=output(run(['query','--ds-id','GA4','--ds-accounts','123','--date-range','last_28_days','--fields','sessions']))
+ assert.equal(r.body.date_range_type,'custom');assert.equal(r.body.start_date,'-28 days');assert.equal(r.body.end_date,'yesterday')
+})
+test('query preview masks credentials and sends no request',()=>{
+ const r=output(run([...query,'--dry-run'],false));assert.equal(r.headers.Authorization,'Bearer ***')
+ assert.equal(JSON.stringify(r).includes('fixture-key'),false)
+})
+test('sources uses the public discovery route',()=>{assert.equal(output(run(['sources','list'])).url,'https://api.supermetrics.com/datasource/search')})
+test('accounts uses query/accounts with an encoded source ID',()=>{
+ const r=output(run(['accounts','list','--ds-id','GA4']));assert.equal(r.url,'https://api.supermetrics.com/query/accounts?ds_id=GA4')
+})
+test('team lookup requires a team ID and uses the management route',()=>{
+ const r=output(run(['teams','get','--team-id','123']));assert.equal(r.url,'https://api.supermetrics.com/v1/teams/123')
+})
+test('users list is scoped to the requested team',()=>{
+ const r=output(run(['users','list','--team-id','123']));assert.equal(r.url,'https://api.supermetrics.com/v1/teams/123/users')
+})
+test('undocumented team list no longer dispatches a fictional endpoint',()=>{
+ assert.match(output(run(['teams','list'],false)).error,/teams get/)
+})
+test('missing team scope fails before a request',()=>{
+ assert.match(output(run(['users','list'],false)).error,/team-id/)
+})
+test('invalid team ID cannot change the resource path',()=>{
+ assert.match(output(run(['teams','get','--team-id','1/users'],false)).error,/team-id/)
+})
+test('empty field IDs are rejected before a query',()=>{
+ assert.match(output(run(['query','--ds-id','GA4','--ds-accounts','123','--date-range','last_month','--fields','sessions,,date'],false)).error,/fields/)
+})
+test('custom dates must be complete before a query',()=>{
+ assert.match(output(run(['query','--ds-id','GA4','--ds-accounts','123','--date-range','custom','--fields','date'],false)).error,/start-date.*end-date/)
+})
+test('provider failure exits unsuccessfully',()=>{
+ const r=run(query,true,401);assert.equal(r.status,1);assert.match(r.stderr,/401/)
+})
diff --git a/tools/clis/supermetrics.js b/tools/clis/supermetrics.js
index b956cf3..b87cc77 100755
--- a/tools/clis/supermetrics.js
+++ b/tools/clis/supermetrics.js
@@ -2,7 +2,7 @@
const rawArgs = process.argv.slice(2)
const API_KEY = process.env.SUPERMETRICS_API_KEY
-const BASE_URL = 'https://api.supermetrics.com/enterprise/v2'
+const BASE_URL = 'https://api.supermetrics.com'
if ((!API_KEY) && rawArgs.length > 0) {
console.error(JSON.stringify({ error: 'SUPERMETRICS_API_KEY environment variable required' }))
@@ -14,10 +14,10 @@ async function api(method, path, body) {
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
- 'x-api-key': API_KEY,
+ 'Authorization': `Bearer ${API_KEY}`,
}
if (args['dry-run']) {
- return { _dry_run: true, method, url, headers: { ...headers, 'x-api-key': '***' }, body: body || undefined }
+ return { _dry_run: true, method, url, headers: { ...headers, Authorization: 'Bearer ***' }, body: body || undefined }
}
const res = await fetch(url, {
method,
@@ -25,6 +25,7 @@ async function api(method, path, body) {
body: body ? JSON.stringify(body) : undefined,
})
const text = await res.text()
+ if (!res.ok) throw new Error(`Supermetrics request failed (${res.status}): ${text}`)
try {
return JSON.parse(text)
} catch {
@@ -68,11 +69,21 @@ async function main() {
if (!dsAccounts) { result = { error: '--ds-accounts required' }; break }
if (!dateRange) { result = { error: '--date-range required (e.g., last_28_days, last_month, this_month, custom)' }; break }
if (!fields) { result = { error: '--fields required (comma-separated field names)' }; break }
+ const fieldIds = fields.split(',').map(f => f.trim())
+ if (fieldIds.some(f => !f)) { result = { error: '--fields must contain nonempty field IDs' }; break }
+ if (dateRange === 'custom' && (!args['start-date'] || !args['end-date'])) {
+ result = { error: '--start-date and --end-date required for a custom date range' }; break
+ }
const body = {
ds_id: dsId,
ds_accounts: dsAccounts,
date_range_type: dateRange,
- fields: fields.split(',').map(f => ({ name: f.trim() })),
+ fields: fieldIds.map(id => ({ id })),
+ }
+ if (dateRange === 'last_28_days') {
+ body.date_range_type = 'custom'
+ body.start_date = '-28 days'
+ body.end_date = 'yesterday'
}
if (args.filter) body.filter = args.filter
if (args['max-rows']) body.max_rows = parseInt(args['max-rows'], 10)
@@ -85,7 +96,7 @@ async function main() {
case 'sources':
switch (sub) {
case 'list':
- result = await api('GET', '/datasources')
+ result = await api('GET', '/datasource/search')
break
default:
result = { error: 'Unknown sources subcommand. Use: list' }
@@ -98,7 +109,7 @@ async function main() {
const dsId = args['ds-id']
if (!dsId) { result = { error: '--ds-id required (e.g., GA4, AW, FB)' }; break }
const params = new URLSearchParams({ ds_id: dsId })
- result = await api('GET', `/datasources/accounts?${params.toString()}`)
+ result = await api('GET', `/query/accounts?${params.toString()}`)
break
}
default:
@@ -108,19 +119,28 @@ async function main() {
case 'teams':
switch (sub) {
+ case 'get': {
+ const id = args['team-id']
+ if (!id || !/^[1-9]\d*$/.test(id)) { result = { error: '--team-id required (positive integer team ID)' }; break }
+ result = await api('GET', `/v1/teams/${id}`)
+ break
+ }
case 'list':
- result = await api('GET', '/teams')
+ result = { error: 'The public API has no teams list endpoint. Use: teams get --team-id <id>' }
break
default:
- result = { error: 'Unknown teams subcommand. Use: list' }
+ result = { error: 'Unknown teams subcommand. Use: get --team-id <id>' }
}
break
case 'users':
switch (sub) {
- case 'list':
- result = await api('GET', '/users')
+ case 'list': {
+ const id = args['team-id']
+ if (!id || !/^[1-9]\d*$/.test(id)) { result = { error: '--team-id required (positive integer team ID)' }; break }
+ result = await api('GET', `/v1/teams/${id}/users`)
break
+ }
default:
result = { error: 'Unknown users subcommand. Use: list' }
}
@@ -138,10 +158,10 @@ async function main() {
list: 'accounts list --ds-id <data-source>',
},
teams: {
- list: 'teams list',
+ get: 'teams get --team-id <id>',
},
users: {
- list: 'users list',
+ list: 'users list --team-id <id>',
},
'data-source-ids': {
'GA4': 'Google Analytics 4',
diff --git a/tools/integrations/supermetrics.md b/tools/integrations/supermetrics.md
index 6067e74..491face 100644
--- a/tools/integrations/supermetrics.md
+++ b/tools/integrations/supermetrics.md
@@ -14,7 +14,7 @@ Marketing data pipeline that connects 200+ marketing platforms. Pulls data from
## Authentication
- **Type**: API Key
-- **Query param**: `api_key={api_key}` or **Header**: `x-api-key: {api_key}`
+- **Query param**: `api_key={api_key}` or **Header**: `Authorization: Bearer {api_key}`
- **Get key**: Supermetrics Hub > API settings at https://hub.supermetrics.com
## Common Agent Operations
@@ -22,16 +22,18 @@ Marketing data pipeline that connects 200+ marketing platforms. Pulls data from
### Query a Data Source
```bash
-POST https://api.supermetrics.com/enterprise/v2/query/data/json
+POST https://api.supermetrics.com/query/data/json
{
"ds_id": "GA4",
"ds_accounts": "123456789",
- "date_range_type": "last_28_days",
+ "date_range_type": "custom",
+ "start_date": "-28 days",
+ "end_date": "yesterday",
"fields": [
- { "name": "sessions" },
- { "name": "pageviews" },
- { "name": "date" }
+ { "id": "sessions" },
+ { "id": "pageviews" },
+ { "id": "date" }
]
}
```
@@ -39,17 +41,17 @@ POST https://api.supermetrics.com/enterprise/v2/query/data/json
### Query with Filters
```bash
-POST https://api.supermetrics.com/enterprise/v2/query/data/json
+POST https://api.supermetrics.com/query/data/json
{
"ds_id": "AW",
"ds_accounts": "123-456-7890",
"date_range_type": "last_month",
"fields": [
- { "name": "campaign_name" },
- { "name": "clicks" },
- { "name": "impressions" },
- { "name": "cost" }
+ { "id": "campaign_name" },
+ { "id": "clicks" },
+ { "id": "impressions" },
+ { "id": "cost" }
],
"max_rows": 100
}
@@ -58,25 +60,25 @@ POST https://api.supermetrics.com/enterprise/v2/query/data/json
### List Available Data Sources
```bash
-GET https://api.supermetrics.com/enterprise/v2/datasources
+GET https://api.supermetrics.com/datasource/search
```
### List Connected Accounts
```bash
-GET https://api.supermetrics.com/enterprise/v2/datasources/accounts?ds_id=GA4
+GET https://api.supermetrics.com/query/accounts?ds_id=GA4
```
-### List Teams
+### Get a Team
```bash
-GET https://api.supermetrics.com/enterprise/v2/teams
+GET https://api.supermetrics.com/v1/teams/{team_id}
```
### List Users
```bash
-GET https://api.supermetrics.com/enterprise/v2/users
+GET https://api.supermetrics.com/v1/teams/{team_id}/users
```
## Key Metrics
@@ -96,7 +98,7 @@ GET https://api.supermetrics.com/enterprise/v2/users
- `HubSpot` - HubSpot
### Date Range Values
-- `last_28_days` - Last 28 days
+- `last_28_days` - CLI shorthand for a custom range from `-28 days` through `yesterday`
- `last_month` - Previous calendar month
- `this_month` - Current month to date
- `custom` - Custom range (requires `start_date` and `end_date`)
@@ -107,7 +109,7 @@ GET https://api.supermetrics.com/enterprise/v2/users
- `ds_id` - Data source identifier (required)
- `ds_accounts` - Account ID for the data source (required)
- `date_range_type` - Date range preset or "custom" (required)
-- `fields` - Array of field objects with `name` property (required)
+- `fields` - Array of field objects with required `id` property (required)
- `filter` - Filter expression for narrowing results
- `max_rows` - Maximum number of rows to return
- `start_date` - Start date for custom range (YYYY-MM-DD)
@@ -143,3 +145,11 @@ GET https://api.supermetrics.com/enterprise/v2/users
- seo-audit
- content-strategy
- social
+
+## CLI Contract Notes
+
+- `teams get --team-id <id>` retrieves one team; `users list --team-id <id>` lists that team's users. These require a key with the corresponding management permissions. The former unscoped `teams list` has no documented public equivalent and now returns migration guidance.
+- Query custom ranges require both `--start-date` and `--end-date`. Field names passed to `--fields` are provider field IDs, not display-name overrides. Empty IDs are rejected before a request.
+- HTTP failures exit unsuccessfully; `--dry-run` masks the Bearer credential without sending any request.
+
+Primary contracts: [authentication](https://docs.supermetrics.com/apidocs/authentication), [fields](https://docs.supermetrics.com/apidocs/fields), [relative dates](https://docs.supermetrics.com/apidocs/date-strings), [query data](https://docs.supermetrics.com/apidocs/query-data-3), [source search](https://docs.supermetrics.com/apidocs/search-data-sources), [accounts](https://docs.supermetrics.com/apidocs/get-accounts), [team lookup](https://docs.supermetrics.com/apidocs/get-team-details-by-team-id), and [team users](https://docs.supermetrics.com/apidocs/list-all-users-in-a-team).