Skip to main content

Analytics API

This page documents the 12 gateway endpoints tagged analytics in the gateway's OpenAPI document. Every example targets a gateway on http://localhost:4000 and authenticates with the SPANWAY_API_KEY environment variable, which holds the master key or a virtual key that has access to the route. Request and response fields are taken from the schema the running gateway publishes at /openapi.json, and the same document is bundled with this site as openapi.json.

MethodPathSummary
POST/analytics/exploreChart a usage metric grouped by up to two dimensions
POST/analytics/queryRun a read only SQL query over the analytics tables
POST/analytics/query/draftDraft an analytics query from a question with Ask AI
GET/analytics/query/helpList the tables and functions an analytics query may use
GET/analytics/savedList saved queries and charts
POST/analytics/savedSave a query or chart
GET/analytics/saved/{query_id}Read one saved query or chart
PATCH/analytics/saved/{query_id}Change a saved query or chart
DELETE/analytics/saved/{query_id}Delete a saved query or chart
GET/analytics/trendsRank what moved most against the previous period
GET/analytics/users/activeDaily active and new end users of your application
GET/analytics/users/retentionWeekly retention of your application's end users

Endpoints​

POST /analytics/explore​

Chart a usage metric grouped by up to two dimensions

Add up one metric, such as spend or requests, from the daily usage tables between two dates, grouped by up to two dimensions such as date and model, with optional filters. Grouping or filtering by user, team, end user or tag reads that table, and only one of them may be used at a time. Rows follow the same role scope as SQL queries and nothing changes. Docs (https://docs.spanway.ai/docs/proxy/analytics_query#explore)

Request body (application/json, schema ExploreRequest):

FieldTypeRequiredDescription
end_datestringYesEnd Date
filtersarray of ExploreFilterNoFilters
group_byarray of enum: "date", "model", "model_group", "provider", "api_key", "endpoint", "mcp_tool", "user", ...NoGroup By
limitintegerNoMost groups returned, largest values first
metricenum: "spend", "requests", "successful_requests", "failed_requests", "tokens", "prompt_tokens", "completion_tokens", "avg_latency_ms"NoMetric
start_datestringYesStart Date

Example request:

curl -X POST "http://localhost:4000/analytics/explore" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"end_date": "2026-11-22",
"group_by": [
"date",
"model"
],
"metric": "spend",
"start_date": "2026-11-01"
}'

Responses:

StatusDescriptionBody
200One row per groupapplication/json ExploreResult
400The dimensions come from different tablesapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key has no gateway user, the role may not do this, or analytics are turned offapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
429Too many queries are running on this gateway instanceapplication/json ErrorDetail
500The gateway runs without a databaseapplication/json ErrorDetail
503The database did not answerapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
group_byarray of enum: "date", "model", "model_group", "provider", "api_key", "endpoint", "mcp_tool", "user", ...YesGroup By
metricenum: "spend", "requests", "successful_requests", "failed_requests", "tokens", "prompt_tokens", "completion_tokens", "avg_latency_ms"YesMetric
rowsarray of ExploreRowYesRows
sourcestringYesThe analytics table the numbers came from
truncatedbooleanYesTruncated

POST /analytics/query​

Run a read only SQL query over the analytics tables

Run one SELECT over the request log and daily usage tables, for example spend per model this week. Admins and admin viewers see every row, other users see their own rows and their permitted teams' rows. The query runs in a read only transaction with a time limit and a row limit, only listed tables and functions are allowed, and prompts, answers, metadata and IP addresses are never readable. Each run writes an audit row with a hash of the SQL. Docs (https://docs.spanway.ai/docs/proxy/analytics_query)

Request body (application/json, schema AnalyticsQueryRequest):

FieldTypeRequiredDescription
max_rowsinteger or nullNoFewer rows than the gateway limit
sqlstringYesOne SELECT statement over the tables GET /analytics/query/help lists

Example request:

curl -X POST "http://localhost:4000/analytics/query" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"sql": "SELECT model, count(*) AS requests, round(sum(spend)::numeric, 4) AS spend FROM spend_logs WHERE start_time > now() - interval '\''7 days'\'' GROUP BY model ORDER BY spend DESC"
}'

Responses:

StatusDescriptionBody
200The rows the query returnedapplication/json AnalyticsQueryResult
400The SQL was refused by the checks, failed in the database or ran past the time limitapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key has no gateway user, the role may not do this, or analytics are turned offapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
429Too many queries are running on this gateway instanceapplication/json ErrorDetail
500The gateway runs without a databaseapplication/json ErrorDetail
503The database did not answerapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
columnsarray of stringYesColumn names in the order the query returned them
elapsed_msintegerYesHow long the database took, in milliseconds
row_countintegerYesNumber of rows returned
rowsarray of array of JsonValueYesThe rows, each value in the column order
truncatedbooleanYesTrue when the query had more rows than the row limit

POST /analytics/query/draft​

Draft an analytics query from a question with Ask AI

Turn a question in plain words into one SQL query over the analytics tables, written by a model on this gateway. The draft is checked like a real run and returned as text, nothing runs until you run it. Proxy admins only, because the model call is billed to the gateway. Each draft writes an audit row. Docs (https://docs.spanway.ai/docs/proxy/analytics_query#ask-ai)

Request body (application/json, schema AnalyticsDraftRequest):

FieldTypeRequiredDescription
modelstringYesA model group on this gateway that writes the draft
questionstringYesThe question in plain words, for example spend per model last week

Example request:

curl -X POST "http://localhost:4000/analytics/query/draft" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.5",
"question": "Which models cost the most this week?"
}'

Responses:

StatusDescriptionBody
200The drafted SQL and whether it passes the checksapplication/json AnalyticsDraft
400The model is not served by this gatewayapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller is not a proxy admin, or analytics are turned offapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
modelstringYesModel
problemstring or nullNoWhy the draft would be refused, when it would be
sqlstringYesThe drafted query. It is not run until you run it
validbooleanYesTrue when the draft passes the same checks a query run does

GET /analytics/query/help​

List the tables and functions an analytics query may use

Describe what POST /analytics/query may read: each table with its columns, which rows your role sees in it, the functions a query may call, the row and time limits and example queries. Any gateway user may call it and nothing changes. Docs (https://docs.spanway.ai/docs/proxy/analytics_query)

Example request:

curl -X GET "http://localhost:4000/analytics/query/help" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200The query reference for the callerapplication/json AnalyticsQueryHelp
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key has no gateway user, the role may not do this, or analytics are turned offapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
examplesarray of AnalyticsExampleYesExamples
functionsarray of stringYesFunctions a query may call
limitsAnalyticsLimitsYes
scopeenum: "all", "owned"Yesall for admins, owned when only your own and team rows show
tablesarray of AnalyticsTableYesTables

GET /analytics/saved​

List saved queries and charts

List your own saved queries and charts plus the ones shared with everyone, newest first. Admins and admin viewers see every item. Nothing changes. Docs (https://docs.spanway.ai/docs/proxy/analytics_query#saved-queries-and-charts)

Example request:

curl -X GET "http://localhost:4000/analytics/saved" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200The saved itemsapplication/json SavedQueryList
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key has no gateway user, the role may not do this, or analytics are turned offapplication/json ErrorDetail
500The gateway runs without a databaseapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
itemsarray of SavedQueryYesItems

POST /analytics/saved​

Save a query or chart

Save a SQL query or an Explore chart under a name. private keeps it to you, shared shows it to everyone who may run queries, and each person who opens it still only sees their own rows. Proxy admins and internal users may save, and the new item is written to the audit log. Docs (https://docs.spanway.ai/docs/proxy/analytics_query#saved-queries-and-charts)

Request body (application/json, schema SavedQueryCreate):

FieldTypeRequiredDescription
definitionSavedSql or SavedChartYesDefinition
descriptionstringNoDescription
namestringYesName
visibilityenum: "private", "shared"NoVisibility

Example request:

curl -X POST "http://localhost:4000/analytics/saved" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"definition": {
"kind": "sql",
"sql": "SELECT model, count(*) AS requests, round(sum(spend)::numeric, 4) AS spend FROM spend_logs WHERE start_time > now() - interval '\''7 days'\'' GROUP BY model ORDER BY spend DESC"
},
"description": "Weekly cost review",
"name": "Spend per model this week",
"visibility": "shared"
}'

Responses:

StatusDescriptionBody
200The saved itemapplication/json SavedQuery
400The owner already has the most saved items allowedapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The role may not save queries, or the item belongs to someone elseapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway runs without a databaseapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
created_atstringYesCreated At
definitionSavedSql or SavedChartYesDefinition
descriptionstringYesDescription
namestringYesName
owner_user_idstring or nullYesOwner User Id
query_idstringYesQuery Id
updated_atstringYesUpdated At
visibilityenum: "private", "shared"YesVisibility

GET /analytics/saved/{query_id}​

Read one saved query or chart

Read a saved query or chart you own, or one shared with everyone. Nothing changes. Docs (https://docs.spanway.ai/docs/proxy/analytics_query#saved-queries-and-charts)

Parameters:

NameInTypeRequiredDescription
query_idpathstringYes

Example request:

curl -X GET "http://localhost:4000/analytics/saved/query_id-123" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200The saved itemapplication/json SavedQuery
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key has no gateway user, the role may not do this, or analytics are turned offapplication/json ErrorDetail
404No saved query has that id, or it is private to someone elseapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway runs without a databaseapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
created_atstringYesCreated At
definitionSavedSql or SavedChartYesDefinition
descriptionstringYesDescription
namestringYesName
owner_user_idstring or nullYesOwner User Id
query_idstringYesQuery Id
updated_atstringYesUpdated At
visibilityenum: "private", "shared"YesVisibility

PATCH /analytics/saved/{query_id}​

Change a saved query or chart

Rename, describe, share, unshare or replace the query or chart of an item you own. Proxy admins may change any item. Fields left out keep their value, and the before and after values go to the audit log. Docs (https://docs.spanway.ai/docs/proxy/analytics_query#saved-queries-and-charts)

Parameters:

NameInTypeRequiredDescription
query_idpathstringYes

Request body (application/json, schema SavedQueryUpdate):

FieldTypeRequiredDescription
definitionSavedSql or SavedChart or nullNoDefinition
descriptionstring or nullNoDescription
namestring or nullNoName
visibilityenum: "private", "shared" or nullNoVisibility

Example request:

curl -X PATCH "http://localhost:4000/analytics/saved/query_id-123" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"visibility": "private"
}'

Responses:

StatusDescriptionBody
200The changed itemapplication/json SavedQuery
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The role may not save queries, or the item belongs to someone elseapplication/json ErrorDetail
404No saved query has that id, or it is private to someone elseapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway runs without a databaseapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
created_atstringYesCreated At
definitionSavedSql or SavedChartYesDefinition
descriptionstringYesDescription
namestringYesName
owner_user_idstring or nullYesOwner User Id
query_idstringYesQuery Id
updated_atstringYesUpdated At
visibilityenum: "private", "shared"YesVisibility

DELETE /analytics/saved/{query_id}​

Delete a saved query or chart

Delete an item you own. Proxy admins may delete any item. The deleted item is returned and written to the audit log. Docs (https://docs.spanway.ai/docs/proxy/analytics_query#saved-queries-and-charts)

Parameters:

NameInTypeRequiredDescription
query_idpathstringYes

Example request:

curl -X DELETE "http://localhost:4000/analytics/saved/query_id-123" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200The deleted itemapplication/json SavedQuery
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The role may not save queries, or the item belongs to someone elseapplication/json ErrorDetail
404No saved query has that id, or it is private to someone elseapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway runs without a databaseapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
created_atstringYesCreated At
definitionSavedSql or SavedChartYesDefinition
descriptionstringYesDescription
namestringYesName
owner_user_idstring or nullYesOwner User Id
query_idstringYesQuery Id
updated_atstringYesUpdated At
visibilityenum: "private", "shared"YesVisibility

Rank what moved most against the previous period

Compare the last days days with the days before them for one metric and one dimension, and list the groups that changed most, for example the models whose spend grew fastest this week. Same role scope as SQL queries, and nothing changes. Docs (https://docs.spanway.ai/docs/proxy/analytics_query#trends)

Parameters:

NameInTypeRequiredDescription
metricqueryenum: "spend", "requests", "successful_requests", "failed_requests", "tokens", "prompt_tokens", "completion_tokens", "avg_latency_ms"NoWhat to compare
dimensionqueryenum: "date", "model", "model_group", "provider", "api_key", "endpoint", "mcp_tool", "user", ...NoWhat to rank
daysqueryintegerNoLength of each period in days
limitqueryintegerNoMost movers returned

Example request:

curl -X GET "http://localhost:4000/analytics/trends" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200The biggest movers firstapplication/json TrendsResult
400date is not a dimension trends can rankapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key has no gateway user, the role may not do this, or analytics are turned offapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
429Too many queries are running on this gateway instanceapplication/json ErrorDetail
500The gateway runs without a databaseapplication/json ErrorDetail
503The database did not answerapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
current_startstringYesCurrent Start
daysintegerYesDays
dimensionenum: "date", "model", "model_group", "provider", "api_key", "endpoint", "mcp_tool", "user", ...YesDimension
metricenum: "spend", "requests", "successful_requests", "failed_requests", "tokens", "prompt_tokens", "completion_tokens", "avg_latency_ms"YesMetric
moversarray of TrendRowYesMovers
previous_startstringYesPrevious Start

GET /analytics/users/active​

Daily active and new end users of your application

Count the end users of your application per day, from the x-spanway-end-user-id header (or the user field) your application sends with each request: how many were active and how many were seen for the first time. Same role scope as SQL queries, and nothing changes. Docs (https://docs.spanway.ai/docs/proxy/analytics_query#end-user-analytics)

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoFirst day, defaults to 29 days ago
end_datequerystring or nullNoLast day, defaults to today

Example request:

curl -X GET "http://localhost:4000/analytics/users/active" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200One entry per dayapplication/json ActiveUsersResult
400The dates are reversed or too far apartapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key has no gateway user, the role may not do this, or analytics are turned offapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
429Too many queries are running on this gateway instanceapplication/json ErrorDetail
500The gateway runs without a databaseapplication/json ErrorDetail
503The database did not answerapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
daysarray of ActiveUsersDayYesDays
total_usersintegerYesDistinct end users over the whole window

GET /analytics/users/retention​

Weekly retention of your application's end users

Group end users by the week they first sent a request, from the x-spanway-end-user-id header, and show which share of each group came back in each later week. Same role scope as SQL queries, and nothing changes. Docs (https://docs.spanway.ai/docs/proxy/analytics_query#end-user-analytics)

Parameters:

NameInTypeRequiredDescription
weeksqueryintegerNoNumber of weekly cohorts

Example request:

curl -X GET "http://localhost:4000/analytics/users/retention" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200One cohort per week, oldest firstapplication/json RetentionResult
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key has no gateway user, the role may not do this, or analytics are turned offapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
429Too many queries are running on this gateway instanceapplication/json ErrorDetail
500The gateway runs without a databaseapplication/json ErrorDetail
503The database did not answerapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
cohortsarray of RetentionCohortYesCohorts
weeksintegerYesWeeks