Skip to main content

Budget & Spend Tracking API

This page documents the 29 gateway endpoints tagged Budget & Spend Tracking 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
GET/user/daily/activityShow a user's daily spend and usage
GET/user/daily/activity/aggregatedDaily activity per user
GET/user/daily/activity/aggregated/keysKeys ranked by spend for a user
GET/user/daily/activity/aggregated/searchSearch the keys with activity for a user
GET/user/daily/activity/aggregated/model_top_keysTop keys for one model in a user
GET/user/daily/activity/exportDownload user daily activity as CSV or JSON
GET/user/daily/activity/aggregated/usersUsers ranked by spend
GET/user/daily/activity/aggregated/cache_leakage_keysKeys that write prompt cache without reading it
GET/management/v1/spend_logs/end_usersList the end users seen in spend logs
GET/management/v1/spend_logs/usersList the users seen in spend logs
GET/spend/tagsSpend per request tag
GET/spend/capture_rateCompare captured spend with the provider bill
GET/global/spend/reportGateway-wide spend report per day
GET/key/spend/reportSpend report for one key
GET/user/spend/reportSpend report for one user
GET/team/spend/reportSpend report for one team
GET/organization/spend/reportSpend report for one organization
GET/global/spend/tagsSpend per tag over a date range
POST/spend/calculateCalculate the cost of a request or a response
GET/spend/logs/uiPage through spend logs with session totals for the Admin UI
GET/spend/logs/v2Page through spend logs
GET/spend/logsSpend logs or daily totals, unpaginated
POST/global/spend/resetReset the spend counters of every key and team
GET/provider/budgetsBudget and spend per provider
POST/add/allowed_ipAdd an address or range to the gateway IP allowlist
POST/delete/allowed_ipRemove an address or range from the gateway IP allowlist
POST/disable/allowed_ipsTurn the gateway IP allowlist off
GET/gateway/daily/activityCount the requests the gateway answered per day
GET/gateway/errors/activityShow failed requests by day, status code and caller

Endpoints​

GET /user/daily/activity​

Show a user's daily spend and usage

Shows spend, tokens and request counts per day between start_date and end_date (YYYY-MM-DD), with a breakdown by model, key and provider, for the Usage page of the Admin UI. Admins see one user with user_id or everyone without it; other keys only see their own spend. Filter further by model or api_key. Read only, nothing changes. This route is in beta and its response may still change.

Reads daily spend records that only ever accumulate and are never affected by budget resets. Their total can legitimately exceed the spend field returned by /v2/user/info, which is a running budget counter that every budget reset sets back to zero (or to the overage above max_budget when budget_rollover is enabled).

What you get back: (by date)

  • spend
  • prompt_tokens
  • completion_tokens
  • cache_read_input_tokens
  • cache_creation_input_tokens
  • total_tokens
  • api_requests
  • breakdown by model, api_key, provider

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoStart date in YYYY-MM-DD format
end_datequerystring or nullNoEnd date in YYYY-MM-DD format
modelquerystring or nullNoFilter by specific model
api_keyquerystring or nullNoFilter by specific API key
user_idquerystring or nullNoFilter by specific user ID. Admins can filter by any user or omit for global view. Non-admins must provide their own user_id.
pagequeryintegerNoPage number for pagination
page_sizequeryintegerNoItems per page
timezonequeryinteger or nullNoTimezone offset in minutes from UTC (e.g., 480 for PST). Matches JavaScript's Date.getTimezoneOffset() convention.
include_current_utc_dayquerybooleanNoWhen the range ends on the caller's current local day, extend it to today's UTC bucket so spend written after the caller's local midnight (in UTC terms) is included. Requires the timezone parameter. Historical ranges are

Example request:

curl -X GET "http://localhost:4000/user/daily/activity" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Spend and tokens per dayapplication/json SpendAnalyticsPaginatedResponse
400start_date or end_date is missingapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ErrorDetail
403A non-admin key asked for another user's spendapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway has no database connectedapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
resultsarray of DailySpendDataYesResults
metadataDailySpendMetadataNo

GET /user/daily/activity/aggregated​

Daily activity per user

Aggregated analytics for a user's daily activity without pagination. Returns the same response shape as the paginated endpoint with page metadata set to single-page.

Reads daily spend records that only ever accumulate and are never affected by budget resets. Their total can legitimately exceed the spend field returned by /v2/user/info, which is a running budget counter that every budget reset sets back to zero (or to the overage above max_budget when budget_rollover is enabled).

Parameters:

NameInTypeRequiredDescription
api_key_limitqueryintegerNoHow many top keys to return
start_datequerystring or nullNoStart date in YYYY-MM-DD format
end_datequerystring or nullNoEnd date in YYYY-MM-DD format
modelquerystring or nullNoFilter by specific model
api_keyquerystring or nullNoFilter by specific API key
user_idquerystring or nullNoFilter by specific user ID. Admins can filter by any user or omit for global view. Non-admins must provide their own user_id.
timezonequeryinteger or nullNoTimezone offset in minutes from UTC (e.g., 480 for PST). Matches JavaScript's Date.getTimezoneOffset() convention.
include_current_utc_dayquerybooleanNoWhen the range ends on the caller's current local day, extend it to today's UTC bucket so spend written after the caller's local midnight (in UTC terms) is included. Requires the timezone parameter. Historical ranges are

Example request:

curl -X GET "http://localhost:4000/user/daily/activity/aggregated" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Successful Responseapplication/json SpendAnalyticsPaginatedResponse
400The date range is invalidapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not read this scopeapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The analytics query failed, the gateway log has the causeapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
resultsarray of DailySpendDataYesResults
metadataDailySpendMetadataNo

GET /user/daily/activity/aggregated/keys​

Keys ranked by spend for a user

One page of the virtual keys that spent the most inside the user scope and date range, with the spend, tokens and request counts of each. offset and limit page through the list and total_api_keys says how many keys there are in all. Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Parameters:

NameInTypeRequiredDescription
offsetqueryintegerNoHow many rows to skip, for paging
limitqueryintegerNoHow many rows to return
start_datequerystring or nullNoStart date in YYYY-MM-DD format
end_datequerystring or nullNoEnd date in YYYY-MM-DD format
modelquerystring or nullNoFilter by specific model
api_keyquerystring or nullNoFilter by specific API key
user_idquerystring or nullNoFilter by specific user ID. Admins can filter by any user or omit for global view. Non-admins must provide their own user_id.
timezonequeryinteger or nullNoTimezone offset in minutes from UTC (e.g., 480 for PST). Matches JavaScript's Date.getTimezoneOffset() convention.
include_current_utc_dayquerybooleanNoWhen the range ends on the caller's current local day, extend it to today's UTC bucket so spend written after the caller's local midnight (in UTC terms) is included. Requires the timezone parameter. Historical ranges are

Example request:

curl -X GET "http://localhost:4000/user/daily/activity/aggregated/keys" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Successful Responseapplication/json DailyActivityKeyPageResponse
400The date range is invalidapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not read this scopeapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The analytics query failed, the gateway log has the causeapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
api_keysarray of KeySpendActivityRowYesApi Keys
total_api_keysintegerYesTotal Api Keys
offsetintegerYesOffset
limitintegerYesLimit

Search the keys with activity for a user

Find virtual keys with activity inside the user scope and date range whose alias, hash, user id or email matches the search text, each with its spend, tokens and request counts. This is the key search box of the Usage page. Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Parameters:

NameInTypeRequiredDescription
searchquerystringYesText to find in key aliases and key hashes
limitqueryintegerNoHow many rows to return
start_datequerystring or nullNoStart date in YYYY-MM-DD format
end_datequerystring or nullNoEnd date in YYYY-MM-DD format
modelquerystring or nullNoFilter by specific model
api_keyquerystring or nullNoFilter by specific API key
user_idquerystring or nullNoFilter by specific user ID. Admins can filter by any user or omit for global view. Non-admins must provide their own user_id.
timezonequeryinteger or nullNoTimezone offset in minutes from UTC (e.g., 480 for PST). Matches JavaScript's Date.getTimezoneOffset() convention.
include_current_utc_dayquerybooleanNoWhen the range ends on the caller's current local day, extend it to today's UTC bucket so spend written after the caller's local midnight (in UTC terms) is included. Requires the timezone parameter. Historical ranges are

Example request:

curl -X GET "http://localhost:4000/user/daily/activity/aggregated/search?search=string" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Successful Responseapplication/json DailyActivityKeySearchResponse
400The date range is invalidapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not read this scopeapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The analytics query failed, the gateway log has the causeapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
api_keysarray of KeyActivityRowYesApi Keys

GET /user/daily/activity/aggregated/model_top_keys​

Top keys for one model in a user

The virtual keys that spent the most on one model inside the user scope and date range. by_model_group tells whether model was matched as the public model group or as the individual deployment. Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Parameters:

NameInTypeRequiredDescription
model_groupquerystringYesThe model or model group to rank keys for
by_model_groupquerybooleanNoMatch model_group as a model group, not a model
limitqueryintegerNoHow many rows to return
start_datequerystring or nullNoStart date in YYYY-MM-DD format
end_datequerystring or nullNoEnd date in YYYY-MM-DD format
modelquerystring or nullNoFilter by specific model
api_keyquerystring or nullNoFilter by specific API key
user_idquerystring or nullNoFilter by specific user ID. Admins can filter by any user or omit for global view. Non-admins must provide their own user_id.
timezonequeryinteger or nullNoTimezone offset in minutes from UTC (e.g., 480 for PST). Matches JavaScript's Date.getTimezoneOffset() convention.
include_current_utc_dayquerybooleanNoWhen the range ends on the caller's current local day, extend it to today's UTC bucket so spend written after the caller's local midnight (in UTC terms) is included. Requires the timezone parameter. Historical ranges are

Example request:

curl -X GET "http://localhost:4000/user/daily/activity/aggregated/model_top_keys?model_group=claude-sonnet-5-5" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Successful Responseapplication/json ModelTopKeysResponse
400The date range is invalidapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not read this scopeapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The analytics query failed, the gateway log has the causeapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
modelstringYesModel
by_model_groupbooleanYesBy Model Group
api_keysarray of KeySpendActivityRowYesApi Keys

GET /user/daily/activity/export​

Download user daily activity as CSV or JSON

Stream one row per day for each user in the range, with requests, tokens and spend. export_type picks the breakdown: daily, daily_with_keys, daily_with_models or daily_with_users. format is csv (the default) or json. The file name carries the entity, the range and the breakdown. This is the Export Data dialog of the Usage page. Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Parameters:

NameInTypeRequiredDescription
export_typequeryExportTypeNoThe breakdown of each row
formatqueryenum: "csv", "json"Nocsv or json
start_datequerystring or nullNoStart date in YYYY-MM-DD format
end_datequerystring or nullNoEnd date in YYYY-MM-DD format
modelquerystring or nullNoFilter by specific model
api_keyquerystring or nullNoFilter by specific API key
user_idquerystring or nullNoFilter by specific user ID. Admins can filter by any user or omit for global view. Non-admins must provide their own user_id.
timezonequeryinteger or nullNoTimezone offset in minutes from UTC (e.g., 480 for PST). Matches JavaScript's Date.getTimezoneOffset() convention.
include_current_utc_dayquerybooleanNoWhen the range ends on the caller's current local day, extend it to today's UTC bucket so spend written after the caller's local midnight (in UTC terms) is included. Requires the timezone parameter. Historical ranges are

Example request:

curl -X GET "http://localhost:4000/user/daily/activity/export" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Streamed daily activity exporttext/csv string
400Bad Requestapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not read this scopeapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The analytics query failed, the gateway log has the causeapplication/json ErrorDetail

GET /user/daily/activity/aggregated/users​

Users ranked by spend

One page of the internal users with activity in the date range, each with spend, tokens and request counts. offset and limit page through the list and total_users says how many users there are in all. Proxy admins and admin viewers see every user, other callers only themselves. Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Parameters:

NameInTypeRequiredDescription
offsetqueryintegerNoHow many rows to skip, for paging
limitqueryintegerNoHow many rows to return
start_datequerystring or nullNoStart date in YYYY-MM-DD format
end_datequerystring or nullNoEnd date in YYYY-MM-DD format
modelquerystring or nullNoFilter by specific model
api_keyquerystring or nullNoFilter by specific API key
user_idquerystring or nullNoFilter by specific user ID. Admins can filter by any user or omit for global view. Non-admins must provide their own user_id.
timezonequeryinteger or nullNoTimezone offset in minutes from UTC (e.g., 480 for PST). Matches JavaScript's Date.getTimezoneOffset() convention.
include_current_utc_dayquerybooleanNoWhen the range ends on the caller's current local day, extend it to today's UTC bucket so spend written after the caller's local midnight (in UTC terms) is included. Requires the timezone parameter. Historical ranges are

Example request:

curl -X GET "http://localhost:4000/user/daily/activity/aggregated/users" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Successful Responseapplication/json DailyActivityUserPageResponse
400The date range is invalidapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not read this scopeapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The analytics query failed, the gateway log has the causeapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
usersarray of UserActivityRowYesUsers
total_usersintegerYesTotal Users
offsetintegerYesOffset
limitintegerYesLimit

GET /user/daily/activity/aggregated/cache_leakage_keys​

Keys that write prompt cache without reading it

The virtual keys in the date range whose requests created prompt cache entries but read few or none back, which means they pay the cache write price without the saving. Use it to find callers whose prompts change on every call. Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Parameters:

NameInTypeRequiredDescription
limitqueryintegerNo
start_datequerystring or nullNoStart date in YYYY-MM-DD format
end_datequerystring or nullNoEnd date in YYYY-MM-DD format
modelquerystring or nullNoFilter by specific model
api_keyquerystring or nullNoFilter by specific API key
user_idquerystring or nullNoFilter by specific user ID. Admins can filter by any user or omit for global view. Non-admins must provide their own user_id.
timezonequeryinteger or nullNoTimezone offset in minutes from UTC (e.g., 480 for PST). Matches JavaScript's Date.getTimezoneOffset() convention.
include_current_utc_dayquerybooleanNoWhen the range ends on the caller's current local day, extend it to today's UTC bucket so spend written after the caller's local midnight (in UTC terms) is included. Requires the timezone parameter. Historical ranges are

Example request:

curl -X GET "http://localhost:4000/user/daily/activity/aggregated/cache_leakage_keys" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Successful Responseapplication/json CacheLeakageKeysResponse
400The date range is invalidapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not read this scopeapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The analytics query failed, the gateway log has the causeapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
api_keysarray of KeySpendActivityRowYesApi Keys

GET /management/v1/spend_logs/end_users​

List the end users seen in spend logs

List the distinct end users, the customer ids sent with requests, that appear in spend logs in a time window, for example to fill the end user filter on the Logs page. Any key may call it. A proxy admin sees every end user in the window, anyone else only end users from their own requests or from teams they administer or hold the /spend/logs permission on. The window is required and at most 10,000 recent rows are scanned, so the query stays fast on a large log table. Nothing changes. Docs

Parameters:

NameInTypeRequiredDescription
filter[startTime][gte]querystringYesWindow start (UTC when no offset is given)
filter[startTime][lte]querystringYesWindow end (UTC when no offset is given)
qquerystring or nullNoCase-insensitive partial match on the end user id
pagequeryintegerNoPage number
page_sizequeryintegerNoPage size

Example request:

curl -X GET "http://localhost:4000/management/v1/spend_logs/end_users?filter[startTime][gte]=string&filter[startTime][lte]=string" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200One page of distinct values, sortedapplication/json FacetListResponse
400A query parameter is unknown or not valid, for example a missing time windowapplication/problem+json any
401No valid key or Admin UI session was presentedapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError
503The gateway database is not connectedapplication/problem+json any

Response fields (200):

FieldTypeRequiredDescription
dataarray of stringYesData
metaPageMetaYeshas_more rather than total_count, which would need a COUNT(*) over the whole match set per keystroke.
linksPageLinksYesHypermedia for a paginated list. No first/last: without a total count the last page is unknown.

GET /management/v1/spend_logs/users​

List the users seen in spend logs

List the distinct internal users that appear in spend logs in a time window, for example to fill the user filter on the Logs page. Any key may call it, and the same scoping as the end users list applies: a proxy admin sees every user, anyone else only users from logs they may read. Nothing changes. Docs

Parameters:

NameInTypeRequiredDescription
filter[startTime][gte]querystringYesWindow start (UTC when no offset is given)
filter[startTime][lte]querystringYesWindow end (UTC when no offset is given)
qquerystring or nullNoCase-insensitive partial match on the internal user id
pagequeryintegerNoPage number
page_sizequeryintegerNoPage size

Example request:

curl -X GET "http://localhost:4000/management/v1/spend_logs/users?filter[startTime][gte]=string&filter[startTime][lte]=string" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200One page of distinct values, sortedapplication/json FacetListResponse
400A query parameter is unknown or not valid, for example a missing time windowapplication/problem+json any
401No valid key or Admin UI session was presentedapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError
503The gateway database is not connectedapplication/problem+json any

Response fields (200):

FieldTypeRequiredDescription
dataarray of stringYesData
metaPageMetaYeshas_more rather than total_count, which would need a COUNT(*) over the whole match set per keystroke.
linksPageLinksYesHypermedia for a paginated list. No first/last: without a total count the last page is unknown.

GET /spend/tags​

Spend per request tag

Total the spend logs by request tag, so you can see what each feature, project or tagged customer spent.

Without dates it covers every row in the spend log. Pass start_date and end_date to limit it to a range. Tags come from the x-spanway-tags header or metadata.tags of each request. Needs a database.

Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoFirst day to include, YYYY-MM-DD
end_datequerystring or nullNoLast day to include, YYYY-MM-DD

Example request:

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

Responses:

StatusDescriptionBody
200One row per tag with its request count and spendapplication/json array of object
400Bad Requestapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

GET /spend/capture_rate​

Compare captured spend with the provider bill

Compare the spend Spanway captured for a provider against that provider's own bill, per UTC day.

A capture_rate of 1.0 means every dollar the provider billed went through the gateway and was priced. A lower rate points at traffic that bypasses the gateway or at models without a price. Proxy admins and admin viewers only. The provider bill is read with the admin credential set on the gateway (OPENAI_ADMIN_KEY for OpenAI), captured spend comes from the daily spend tables, and a range of 180 days or more is a 400.

Docs

Parameters:

NameInTypeRequiredDescription
start_datequerystringYesFirst UTC day of the range, YYYY-MM-DD
end_datequerystringYesLast UTC day of the range, YYYY-MM-DD, inclusive
providerquery"openai"NoProvider whose bill to compare against; needs OPENAI_ADMIN_KEY set on the proxy
thresholdquerynumberNoRatio under which the report flags below_threshold
project_idsqueryarray of string or nullNoScope the OpenAI bill to these project ids; omit to compare against the whole organization. Captured spend is never scoped, so pass every project Spanway's OpenAI keys belong to

Example request:

curl -X GET "http://localhost:4000/spend/capture_rate?start_date=string&end_date=string" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200The capture rate for the range and for each UTC day in itapplication/json CaptureRateReport
400The range is reversed or longer than 180 daysapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller is not a proxy admin or admin viewerapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway has no databaseapplication/json ErrorDetail
502The provider answered the bill request with an errorapplication/json ErrorDetail
503The admin credential that reads the provider bill is not setapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
provider"openai"YesProvider
start_datestringYesStart Date
end_datestringYesEnd Date
captured_spendnumberYesCaptured Spend
provider_spendnumberYesProvider Spend
capture_ratenumber or nullYesCapture Rate
thresholdnumberYesThreshold
below_thresholdbooleanYesBelow Threshold
daysarray of CaptureRateDayYesDays

GET /global/spend/report​

Gateway-wide spend report per day

Report the whole gateway's spend per day over a date range, grouped by team, customer or key.

Proxy admins, admin viewers and keys with the get_spend_routes permission can call it. It needs a license that includes spend_reports and a database. Pass api_key (as a sha256 hash), internal_user_id, team_id or customer_id to narrow the report to one scope, in which case the rows take the per-key shape of /team/spend/report. The grouped shape per day looks like this: [ { "group-by-day": "2024-05-10", "teams": [ { "team_name": "team-1" "spend": 10, "keys": [ "key": "1213", "usage": { "model-1": { "cost": 12.50, "input_tokens": 1000, "output_tokens": 5000, "requests": 100 }, "audio-modelname1": { "cost": 25.50, "seconds": 25, "requests": 50 }, } } ] ] }

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoFirst day to include, YYYY-MM-DD
end_datequerystring or nullNoLast day to include, YYYY-MM-DD
group_byqueryenum: "team", "customer", "api_key" or nullNoGroup spend by internal team or customer or api_key
api_keyquerystring or nullNoView spend for a specific api_key. Pass the key's sha256 hash so the raw key stays out of URLs and access logs. Example api_key='d5345c0ecc68ae6295c69f91926b2bd379e25481a40c34b5884d157a9f65d8fa'
internal_user_idquerystring or nullNoView spend for a specific internal_user_id. Example internal_user_id='1234
team_idquerystring or nullNoView spend for a specific team_id. Example team_id='1234
customer_idquerystring or nullNoView spend for a specific customer_id. Example customer_id='1234. Can be used in conjunction with team_id as well.

Example request:

curl -X GET "http://localhost:4000/global/spend/report" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200One entry per day, grouped as requested, or the per-key rows when a scope filter is setapplication/json array of object
400A date is missing or malformed, the range is reversed or longer than 366 days, or the key has no scopeapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The license lacks spend_reports, or the caller asked for someone else's spendapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway has no databaseapplication/json ErrorDetail

GET /key/spend/report​

Spend report for one key

Total what one key spent between start_date and end_date (both inclusive, UTC), broken down by model.

Any key can call it for itself. Proxy admins and admin viewers may pass api_key to report on another key, as its sha256 hash, and a raw key starting with sk- is hashed for you. Needs a license that includes spend_reports and a database. The range covers at most 366 days.

Docs (https://docs.spanway.ai/docs/proxy/spend_reports)

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoTime from which to start viewing spend (YYYY-MM-DD)
end_datequerystring or nullNoTime till which to view spend (YYYY-MM-DD)
api_keyquerystring or nullNoView spend for a specific api_key. Proxy admins and admin viewers only; other callers are scoped to their own key. Pass the key's sha256 hash so the raw key stays out of URLs and access logs. Example api_key='d5345c0ecc6

Example request:

curl -X GET "http://localhost:4000/key/spend/report" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200One row per key in the scope, each with a per-model breakdownapplication/json array of object
400A date is missing or malformed, the range is reversed or longer than 366 days, or the key has no scopeapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The license lacks spend_reports, or the caller asked for someone else's spendapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway has no databaseapplication/json ErrorDetail

GET /user/spend/report​

Spend report for one user

Get spend for the calling user over a date range, grouped by api_key with a per-model breakdown.

Same row shape as /global/spend/report?internal_user_id=..., but callable by any key with a user: non-admin callers are always scoped to their own user_id, while proxy admins may pass ?internal_user_id= to view any user.

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoTime from which to start viewing spend (YYYY-MM-DD)
end_datequerystring or nullNoTime till which to view spend (YYYY-MM-DD)
internal_user_idquerystring or nullNoView spend for a specific internal_user_id. Proxy admins and admin viewers only; other callers are scoped to their own user_id.

Example request:

curl -X GET "http://localhost:4000/user/spend/report" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200One row per key in the scope, each with a per-model breakdownapplication/json array of object
400A date is missing or malformed, the range is reversed or longer than 366 days, or the key has no scopeapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The license lacks spend_reports, or the caller asked for someone else's spendapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway has no databaseapplication/json ErrorDetail

GET /team/spend/report​

Spend report for one team

Get spend for the calling key's team over a date range, grouped by api_key with a per-model breakdown.

Callable by any key that belongs to a team: non-admin callers are always scoped to their key's team_id, while proxy admins may pass ?team_id= to view any team.

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoTime from which to start viewing spend (YYYY-MM-DD)
end_datequerystring or nullNoTime till which to view spend (YYYY-MM-DD)
team_idquerystring or nullNoView spend for a specific team_id. Proxy admins and admin viewers only; other callers are scoped to their key's team.

Example request:

curl -X GET "http://localhost:4000/team/spend/report" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200One row per key in the scope, each with a per-model breakdownapplication/json array of object
400A date is missing or malformed, the range is reversed or longer than 366 days, or the key has no scopeapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The license lacks spend_reports, or the caller asked for someone else's spendapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway has no databaseapplication/json ErrorDetail

GET /organization/spend/report​

Spend report for one organization

Get spend for an organization over a date range, grouped by api_key with a per-model and per-team breakdown.

Covers spend logged against the organization directly and against any of its teams. Callable by proxy admins (any organization) and org admins (their own organizations). Defaults to the calling key's organization_id when ?organization_id= is omitted.

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoTime from which to start viewing spend (YYYY-MM-DD)
end_datequerystring or nullNoTime till which to view spend (YYYY-MM-DD)
organization_idquerystring or nullNoView spend for a specific organization_id. Proxy admins may pass any organization; org admins are scoped to organizations they administer.

Example request:

curl -X GET "http://localhost:4000/organization/spend/report" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200One row per key in the scope, each with a per-model breakdownapplication/json array of object
400A date is missing or malformed, the range is reversed or longer than 366 days, or the key has no scopeapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The license lacks spend_reports, or the caller asked for someone else's spendapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway has no databaseapplication/json ErrorDetail

GET /global/spend/tags​

Spend per tag over a date range

Total spend per tag and day between start_date and end_date, optionally only for the tags listed.

This is the query behind the Tag Usage view of the Admin UI. Both dates are required and a request without them is a 400. Needs a database.

Example Request:

curl -X GET "http://0.0.0.0:4000/spend/tags" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Spend with Start Date and End Date

curl -X GET "http://0.0.0.0:4000/spend/tags?start_date=2022-01-01&end_date=2022-02-01" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoFirst day to include, YYYY-MM-DD
end_datequerystring or nullNoLast day to include, YYYY-MM-DD
tagsquerystring or nullNoComma separated tags to keep, every tag when left out

Example request:

curl -X GET "http://localhost:4000/global/spend/tags" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200One row per tag and day with its request count and spendapplication/json array of object
400Bad Requestapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError
500Internal Server Errorapplication/json ErrorDetail

POST /spend/calculate​

Calculate the cost of a request or a response

Price a request before you send it, or a response you already have, without calling a provider.

Send model and messages to estimate a call from its prompt, or completion_response (a full chat completion object) to price what a provider returned. A model group or alias is resolved to its deployment, and prices set on the deployment in spanway_params or model_info, its base_model and the cache rates are used the way a real request uses them. A model with no price answers 400 and needs custom pricing.

curl --location 'http://localhost:4000/spend/calculate'
--header "Authorization: Bearer $SPANWAY_MASTER_KEY"
--header 'Content-Type: application/json'
--data '{
"model": "anthropic.claude-v2",
"messages": [{"role": "user", "content": "Hey, how'''s it going?"}]
}'

Calculate spend after making call:

curl --location 'http://localhost:4000/spend/calculate'
--header "Authorization: Bearer $SPANWAY_MASTER_KEY"
--header 'Content-Type: application/json'
--data '{
"completion_response": {
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"model": "gpt-3.5-turbo-0125",
"system_fingerprint": "fp_44709d6fcb",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello there, how may I assist you today?"
},
"logprobs": null,
"finish_reason": "stop"
}]
"usage": {
"prompt_tokens": 9,
"completion_tokens": 12,
"total_tokens": 21
}
}
}'

Request body (application/json, schema SpendCalculateRequest):

FieldTypeRequiredDescription
modelstring or nullNoThe model to price, as named on the gateway
messagesarray of any or nullNoThe chat messages to estimate the prompt cost of
completion_responseobject or nullNoA full chat completion response to price

Example request:

curl -X POST "http://localhost:4000/spend/calculate" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"messages": [
{
"role": "user",
"content": "Where is my order?"
}
]
}'

Responses:

StatusDescriptionBody
200The calculated costapplication/json object
400The body names neither a model nor a response, or the model has no priceapplication/json ProxyError
401No valid key or Admin UI session was presentedapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
costnumberNoThe cost in US dollars the gateway would record

GET /spend/logs/ui​

Page through spend logs with session totals for the Admin UI

Read the spend log page by page, filtered by key, user, team, model, status, tags or spend.

start_date and end_date are required, as YYYY-MM-DD or YYYY-MM-DD HH:MM:SS in UTC. A caller that is not a proxy admin sees only their own rows and the rows of teams that let them read logs. page_size goes up to 1000 and total is capped at 10000 rows. Request and response bodies are present only when general_settings.store_prompts_in_spend_logs is on.

Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Example:

curl -X GET "http://0.0.0.0:8000/spend/logs/v2?start_date=2025-11-25%2000:00:00&end_date=2025-11-26%2023:59:59&page=1&page_size=50" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Parameters:

NameInTypeRequiredDescription
api_keyquerystring or nullNoGet spend logs based on api key
user_idquerystring or nullNoGet spend logs based on user_id
request_idquerystring or nullNorequest_id to get spend logs for specific request_id
session_idquerystring or nullNoFilter spend logs by session_id (partial string match)
team_idquerystring or nullNoFilter spend logs by team_id
min_spendquerynumber or nullNoFilter logs with spend greater than or equal to this value
max_spendquerynumber or nullNoFilter logs with spend less than or equal to this value
start_datequerystring or nullNoTime from which to start viewing key spend
end_datequerystring or nullNoTime till which to view key spend
pagequeryintegerNoPage number for pagination
page_sizequeryintegerNoNumber of items per page
status_filterquerystring or nullNoFilter logs by status (e.g., success, failure)
cache_hit_filterquerystring or nullNoFilter logs by cache state: 'hit' or 'miss'. Miss includes legacy rows with a null/unknown cache state
used_client_oauth_tokenqueryboolean or nullNoFilter logs by the credential the upstream call used: true for a client-forwarded Anthropic OAuth token, false for the deployment's configured key. Rows written before this flag existed match neither
span_typequerystring or nullNoFilter logs by span type: llm, agent, mcp, or batch
modelquerystring or nullNoFilter logs by model
model_idquerystring or nullNoFilter logs by model ID (spanway model deployment id)
model_groupquerystring or nullNoFilter logs by model group
key_aliasquerystring or nullNoFilter logs by key alias
end_userquerystring or nullNoFilter logs by end user
error_codequerystring or nullNoFilter logs by error code (e.g., '404', '500')
error_messagequerystring or nullNoFilter logs by error message (partial string match)
sort_byquerystringNoSort logs by field: spend, total_tokens, startTime, endTime, request_duration_ms, model, or ttft_ms
sort_orderquerystring or nullNoSort order: asc or desc
exclude_internal_health_checksquerybooleanNoExclude Spanway internal health check requests from results
group_by_sessionquerybooleanNoPaginate over sessions instead of raw logs: one representative row per session, total counts sessions
session_cursorquerystring or nullNoKeyset cursor '<last_activity>|<api_key>|<session_key>' from a previous group_by_session page. UI route only, honored when sorting by startTime
searchquerystring or nullNoMatch a log whose request_id, spanway_call_id, api_key (hash), team_id, user, end_user, session_id, or model_id equals this value. request_id matches across all time; the other columns match inside start_date/end_date, w

Example request:

curl -X GET "http://localhost:4000/spend/logs/ui" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200A page of spend log rows with the paging countsapplication/json SpendLogsPage
400Bad Requestapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403A non-admin asked for a team or a request it may not readapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError
500The gateway has no databaseapplication/json ProxyError

Response fields (200):

FieldTypeRequiredDescription
dataarray of UiSpendLogRowYesData
totalintegerYesMatching rows, clamped to the pagination count cap when total_is_capped is true
pageintegerYesPage
page_sizeintegerYesPage Size
total_pagesintegerYesTotal Pages
total_is_cappedbooleanNoTotal Is Capped
next_session_cursorstring or nullNoCursor for the next group_by_session page
has_moreboolean or nullNoWhether another group_by_session page exists

GET /spend/logs/v2​

Page through spend logs

Read the spend log page by page, filtered by key, user, team, model, status, tags or spend.

start_date and end_date are required, as YYYY-MM-DD or YYYY-MM-DD HH:MM:SS in UTC. A caller that is not a proxy admin sees only their own rows and the rows of teams that let them read logs. page_size goes up to 1000 and total is capped at 10000 rows. Request and response bodies are present only when general_settings.store_prompts_in_spend_logs is on.

Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Example:

curl -X GET "http://0.0.0.0:8000/spend/logs/v2?start_date=2025-11-25%2000:00:00&end_date=2025-11-26%2023:59:59&page=1&page_size=50" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Parameters:

NameInTypeRequiredDescription
api_keyquerystring or nullNoGet spend logs based on api key
user_idquerystring or nullNoGet spend logs based on user_id
request_idquerystring or nullNorequest_id to get spend logs for specific request_id
session_idquerystring or nullNoFilter spend logs by session_id (partial string match)
team_idquerystring or nullNoFilter spend logs by team_id
min_spendquerynumber or nullNoFilter logs with spend greater than or equal to this value
max_spendquerynumber or nullNoFilter logs with spend less than or equal to this value
start_datequerystring or nullNoTime from which to start viewing key spend
end_datequerystring or nullNoTime till which to view key spend
pagequeryintegerNoPage number for pagination
page_sizequeryintegerNoNumber of items per page
status_filterquerystring or nullNoFilter logs by status (e.g., success, failure)
cache_hit_filterquerystring or nullNoFilter logs by cache state: 'hit' or 'miss'. Miss includes legacy rows with a null/unknown cache state
used_client_oauth_tokenqueryboolean or nullNoFilter logs by the credential the upstream call used: true for a client-forwarded Anthropic OAuth token, false for the deployment's configured key. Rows written before this flag existed match neither
span_typequerystring or nullNoFilter logs by span type: llm, agent, mcp, or batch
modelquerystring or nullNoFilter logs by model
model_idquerystring or nullNoFilter logs by model ID (spanway model deployment id)
model_groupquerystring or nullNoFilter logs by model group
key_aliasquerystring or nullNoFilter logs by key alias
end_userquerystring or nullNoFilter logs by end user
error_codequerystring or nullNoFilter logs by error code (e.g., '404', '500')
error_messagequerystring or nullNoFilter logs by error message (partial string match)
sort_byquerystringNoSort logs by field: spend, total_tokens, startTime, endTime, request_duration_ms, model, or ttft_ms
sort_orderquerystring or nullNoSort order: asc or desc
exclude_internal_health_checksquerybooleanNoExclude Spanway internal health check requests from results
group_by_sessionquerybooleanNoPaginate over sessions instead of raw logs: one representative row per session, total counts sessions
session_cursorquerystring or nullNoKeyset cursor '<last_activity>|<api_key>|<session_key>' from a previous group_by_session page. UI route only, honored when sorting by startTime
searchquerystring or nullNoMatch a log whose request_id, spanway_call_id, api_key (hash), team_id, user, end_user, session_id, or model_id equals this value. request_id matches across all time; the other columns match inside start_date/end_date, w

Example request:

curl -X GET "http://localhost:4000/spend/logs/v2" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200A page of spend log rows with the paging countsapplication/json SpendLogsPage
400Bad Requestapplication/json ErrorDetail
401Unauthorizedapplication/json ErrorDetail
403A non-admin asked for a team or a request it may not readapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError
500The gateway has no databaseapplication/json ProxyError

Response fields (200):

FieldTypeRequiredDescription
dataarray of UiSpendLogRowYesData
totalintegerYesMatching rows, clamped to the pagination count cap when total_is_capped is true
pageintegerYesPage
page_sizeintegerYesPage Size
total_pagesintegerYesTotal Pages
total_is_cappedbooleanNoTotal Is Capped
next_session_cursorstring or nullNoCursor for the next group_by_session page
has_moreboolean or nullNoWhether another group_by_session page exists

GET /spend/logs​

Spend logs or daily totals, unpaginated

Return spend log rows for a key, a user, a request id or a date range in one answer, capped at 10000 rows.

With start_date and end_date and the default summarize=true it returns one total per day instead of rows, and summarize=false returns the rows themselves. Use /spend/logs/v2 for paging and filters, this route is kept for scripts that export a day at a time. A caller that is not a proxy admin only sees their own rows, and a key with no user that is not a proxy admin is refused with 403.

Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Example Request for all logs

curl -X GET "http://0.0.0.0:8000/spend/logs" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Example Request for specific request_id

curl -X GET "http://0.0.0.0:8000/spend/logs?request_id=chatcmpl-6dcb2540-d3d7-4e49-bb27-291f863f112e" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Example Request for specific api_key

curl -X GET "http://0.0.0.0:8000/spend/logs?api_key=d5345c0ecc68ae6295c69f91926b2bd379e25481a40c34b5884d157a9f65d8fa" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Example Request for specific user_id

curl -X GET "http://0.0.0.0:8000/spend/logs?user_id=user@example.com" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Example Request for date range with individual logs (unsummarized)

curl -X GET "http://0.0.0.0:8000/spend/logs?start_date=2024-01-01&end_date=2024-01-02&summarize=false" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Parameters:

NameInTypeRequiredDescription
api_keyquerystring or nullNoGet spend logs based on api key
user_idquerystring or nullNoGet spend logs based on user_id
request_idquerystring or nullNorequest_id to get spend logs for specific request_id. If none passed then pass spend logs for all requests
start_datequerystring or nullNoTime from which to start viewing key spend
end_datequerystring or nullNoTime till which to view key spend
summarizequerybooleanNoWhen start_date and end_date are provided, summarize=true returns aggregated data by date (legacy behavior), summarize=false returns filtered individual logs

Example request:

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

Responses:

StatusDescriptionBody
200Spend log rows, newest firstapplication/json array of Spanway_SpendLogs
400A date is not in YYYY-MM-DD formapplication/json ProxyError
401No valid key or Admin UI session was presentedapplication/json ProxyError
403A key that belongs to no user and is not a proxy adminapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway has no databaseapplication/json ProxyError

POST /global/spend/reset​

Reset the spend counters of every key and team

Set the running spend of every key and every team back to 0, without touching the spend log.

The spend log keeps every row, so reports and exports still show what was spent. Only the budget counters that max_budget is checked against start again. Only the master key may call it, a proxy admin's own key gets a 401. Two audit rows record the reset, one for keys and one for teams, each with the total spend and the number of rows before the reset.

Docs (https://docs.spanway.ai/docs/proxy/spend_logs_export)

Request body (application/json, object):

Example request:

curl -X POST "http://localhost:4000/global/spend/reset" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{}'

Responses:

StatusDescriptionBody
200Confirmation that the counters were resetapplication/json object
401Only the master key may reset spend, a proxy admin's own key is refusedapplication/json ProxyError
500The gateway has no databaseapplication/json ProxyError

Response fields (200):

FieldTypeRequiredDescription
messagestringNo
statusstringNo

GET /provider/budgets​

Budget and spend per provider

Show the budget limit, period, spend so far and next reset time of every provider that has a budget.

Provider budgets are set in the router settings and route traffic away from a provider that has spent its budget, see provider budget routing.

Example Request

curl -X GET http://localhost:4000/provider/budgets -H "Content-Type: application/json" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Example Response

{
"providers": {
"openai": {
"budget_limit": 1e-12,
"time_period": "1d",
"spend": 0.0,
"budget_reset_at": null
},
"azure": {
"budget_limit": 100.0,
"time_period": "1d",
"spend": 0.0,
"budget_reset_at": null
},
"anthropic": {
"budget_limit": 100.0,
"time_period": "10d",
"spend": 0.0,
"budget_reset_at": null
},
"vertex_ai": {
"budget_limit": 100.0,
"time_period": "12d",
"spend": 0.0,
"budget_reset_at": null
}
}
}

Example request:

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

Responses:

StatusDescriptionBody
200Every provider with a budget, its limit, period, spend so far and next resetapplication/json ProviderBudgetResponse
401No valid key or Admin UI session was presentedapplication/json ProxyError

Response fields (200):

FieldTypeRequiredDescription
providersobjectNoThe budget of each provider, by provider name

POST /add/allowed_ip​

Add an address or range to the gateway IP allowlist

Allow one more client address or CIDR range to call the gateway. The change takes effect at once, is saved to the database config so it survives a restart, and is written to the audit log. Needs store_model_in_db, the ip_allowlist license feature and a proxy admin.

Docs (https://docs.spanway.ai/docs/proxy/allow_lists)

Request body (application/json, schema IPAddress):

FieldTypeRequiredDescription
ipstringYesIp

Example request:

curl -X POST "http://localhost:4000/add/allowed_ip" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"ip": "203.0.113.0/24"
}'

Responses:

StatusDescriptionBody
200The address is allowed and the change is saved and auditedapplication/json AllowedIPChanged
400The address is already in the list, or is not an address or CIDR rangeapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key is an admin viewer key, is not a proxy admin key, or the license lacks the ip_allowlist featureapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500store_model_in_db is off or no database is connected, the live list is unchangedapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
messagestringYesMessage
status"success"YesStatus

POST /delete/allowed_ip​

Remove an address or range from the gateway IP allowlist

Stop allowing a client address or CIDR range. The last address cannot be removed, because an empty list would block every request including the Admin UI. The change is saved and written to the audit log. Needs store_model_in_db and a proxy admin.

Docs (https://docs.spanway.ai/docs/proxy/allow_lists)

Request body (application/json, schema IPAddress):

FieldTypeRequiredDescription
ipstringYesIp

Example request:

curl -X POST "http://localhost:4000/delete/allowed_ip" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"ip": "203.0.113.0/24"
}'

Responses:

StatusDescriptionBody
200The address is no longer allowed and the change is saved and auditedapplication/json AllowedIPChanged
400This is the last address. Add another first, or turn the allowlist offapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key is an admin viewer key or is not a proxy admin keyapplication/json ErrorDetail
404The address is not in the listapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500store_model_in_db is off, the live list is unchangedapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
messagestringYesMessage
status"success"YesStatus

POST /disable/allowed_ips​

Turn the gateway IP allowlist off

Turns the gateway IP allowlist off so requests from every IP address are allowed again, and removes the saved list. Use it when the list locked out an address that must stay allowed. It refuses with 400 when allowed_ips is set in the config file, which has to be edited there instead. The change is written to the audit log. Only proxy admins may call it, and it needs the ip_allowlist license feature and store_model_in_db.

Docs (https://docs.spanway.ai/docs/proxy/allow_lists)

Request body (application/json, schema TurnOffAllowedIPsRequest):

FieldTypeRequiredDescription
confirmtrueYesMust be true. Confirms that every IP address will be allowed once the allowlist is off.

Example request:

curl -X POST "http://localhost:4000/disable/allowed_ips" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"confirm": true
}'

Responses:

StatusDescriptionBody
200Every address is allowed again and the saved list is removedapplication/json TurnOffAllowedIPsResponse
400allowed_ips is set in the config file, which has to be edited insteadapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key is an admin viewer key, is not a proxy admin key, or the license lacks the ip_allowlist featureapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500store_model_in_db is off or no database is connected, the live list is unchangedapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
messagestringYesMessage
status"success"YesStatus

GET /gateway/daily/activity​

Count the requests the gateway answered per day

Count the model, MCP and agent requests the gateway answered, successful and failed, per day, per route and per error status code. The counts are taken as each answer leaves the gateway, so they include requests that never reached a model, such as ones refused for a bad key or a rate limit. Without dates the last 30 days are counted.

The totals cover the whole deployment with no split by key, user or team, so only a proxy admin or an admin viewer may call it. Nothing is changed.

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoStart date in YYYY-MM-DD format
end_datequerystring or nullNoEnd date in YYYY-MM-DD format

Example request:

curl -X GET "http://localhost:4000/gateway/daily/activity" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Successful Responseapplication/json GatewayRequestActivityResponse
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key's role, grants or license do not allow this actionapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway hit an internal error, usually the database is not connectedapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
total_successful_requestsintegerNoTotal Successful Requests
total_failed_requestsintegerNoTotal Failed Requests
by_datearray of GatewayRequestDailyEntryNoBy Date
by_routearray of GatewayRequestBreakdownEntryNoBy Route
by_status_codearray of GatewayRequestStatusCodeEntryNoBy Status Code

GET /gateway/errors/activity​

Show failed requests by day, status code and caller

Shows how many requests the gateway refused or failed, so an operator can spot an outage or a misconfigured client quickly. You get the daily totals split into client errors (4xx) and server errors (5xx), the count for each HTTP status code, and the 25 keys, teams, users and model groups with the most failures, each with the status code it failed with most. Leave the dates out to see the last 30 days. It covers the whole deployment, so only the proxy admin and proxy admin viewer roles may call it. Nothing is changed.

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoStart date in YYYY-MM-DD format
end_datequerystring or nullNoEnd date in YYYY-MM-DD format

Example request:

curl -X GET "http://localhost:4000/gateway/errors/activity" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Successful Responseapplication/json RequestErrorActivityResponse
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The key's role, grants or license do not allow this actionapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The gateway hit an internal error, usually the database is not connectedapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
total_successful_requestsintegerNoSuccessful requests over the whole range
total_failed_requestsintegerNoFailed requests over the whole range
by_datearray of RequestErrorDailyEntryNoTotals per day
by_status_codearray of RequestErrorStatusCodeEntryNoFailures per status code, most frequent first
by_keyarray of RequestErrorEntityEntryNoThe keys with the most failures
by_teamarray of RequestErrorEntityEntryNoThe teams with the most failures
by_userarray of RequestErrorEntityEntryNoThe users with the most failures
by_modelarray of RequestErrorEntityEntryNoThe model groups with the most failures