Skip to main content

Key management API

This page documents the 17 gateway endpoints tagged key management 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/key/generateCreate a virtual key
POST/key/service-account/generateCreate a service account key for a team
POST/key/updateUpdate a virtual key
POST/key/bulk_updateUpdate several keys at once
POST/team/key/bulk_updateUpdate every key of a team
POST/key/deleteDelete virtual keys
GET/key/infoGet a key's settings and spend
POST/key/regenerateRotate a virtual key
POST/key/{key}/regenerateRotate a virtual key
POST/key/{key}/reset_spendReset a key's recorded spend
GET/key/listList virtual keys
GET/key/aliasesList the key aliases the caller can see
POST/key/blockBlock a key
POST/key/unblockUnblock a key
POST/key/healthCheck a key's logging settings
GET/key/hygiene/summaryCount the keys each hygiene finding flags
GET/key/hygieneList the keys with one hygiene finding

Endpoints​

POST /key/generate​

Create a virtual key

Create a virtual key, the sk- key an app or person uses to call models through the gateway, with its own models, budget, rate limits and expiry. Proxy admins may create any key. Other users may create keys for themselves or for teams where their role and the team's settings allow it. The new key is shown once in the answer, and the creation is written to the audit log. Docs

What to send:

  • duration: Specify the length of time the token is valid for. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d").
  • key_alias: User defined key alias
  • key: User defined key value. Must start with 'sk-' and be at least 16 characters long. If not set, a 16-digit unique sk-key is created for you.
  • team_id: The team id of the key
  • user_id: The user id of the key
  • agent_id: The agent id associated with the key.
  • organization_id: The organization id of the key. If not set, and team_id is set, the organization id will be the same as the team id. If conflict, an error will be raised.
  • project_id: The project id of the key. When set, models and max_budget are validated against the project's limits.
  • budget_id: The budget id associated with the key. Created by calling /budget/new.
  • end_user_budget_id: Proxy admin only. Budget id applied to end users first seen through this key that carry no budget of their own. Takes precedence over spanway_settings.max_end_user_budget_id.
  • allowed_ips: IP addresses or CIDR ranges the key may be used from, at most 256 entries. A request from any other client address is refused. Example - ["10.0.0.5", "10.0.0.0/8", "2001:db8::/32"]
  • data_policy: Data policy every request on the key must satisfy: require_zdr, forbid_training, restrict_code_traffic, scan_content_for_code and allowed_regions. The router drops every deployment that does not meet it. Example - {"require_zdr": true, "allowed_regions": ["eu"]}
  • models: Model_name's a user is allowed to call. (if empty, key is allowed to call all models)
  • aliases: Any alias mappings, on top of anything in the config.yaml model list. - https://docs.spanway.ai/docs/proxy/virtual_keys#managing-auth---upgradedowngrade-models
  • config: any key-specific configs, overrides config in config.yaml
  • spend: Amount spent by key. Default is 0. Will be updated by proxy whenever key is used. https://docs.spanway.ai/docs/proxy/virtual_keys#managing-auth---tracking-spend
  • send_invite_email: Whether to send an invite email to the user_id, with the generate key
  • max_budget: Specify max budget for a given key.
  • budget_duration: Budget is reset at the end of specified duration. If not set, budget is never reset. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d").
  • max_parallel_requests: Rate limit a user based on the number of parallel requests. Raises 429 error, if user's parallel requests > x.
  • metadata: Metadata for key, store information for key. Example metadata = {"team": "core-infra", "app": "app2", "email": "user@example.com" }
  • guardrails: List of active guardrails for the key
  • policies: List of policy names to apply to the key. Policies define guardrails, conditions, and inheritance rules.
  • disable_global_guardrails: Whether to disable global guardrails for the key. Proxy admin only.
  • throttle_on_budget_exceeded: When the key exceeds its max_budget, throttle its tpm/rpm to the global budget_exceeded_throttle_percentage instead of blocking the key entirely.
  • enable_prompt_caching: Auto-inject prompt caching breakpoints (Anthropic cache_control markers) on requests made with this key. Supported Claude models on Anthropic, Bedrock, Vertex AI, and Azure AI only.
  • provider_preferences: Default provider preferences (order, only, ignore, sort, max_price, allow_fallbacks) for this key's chat, responses, messages, completions and embeddings requests. A request's own provider object can narrow them but never widen them. Proxy admin only. Stored in metadata.
  • permissions: key-specific permissions. Currently just used for turning off pii masking (if connected). Example
    • {"pii": false}
  • model_max_budget: Model-specific budgets {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}}}. IF null or {} then no model specific budget.
  • budget_fallbacks: Per-model fallback chain tried in order when that model's own model_max_budget is exceeded, e.g. {"gpt-4o": ["gpt-4o-mini"]}.
  • model_rpm_limit: key-specific model rpm limit. Example - {"text-davinci-002": 1000, "gpt-3.5-turbo": 1000}. IF null or {} then no model specific rpm limit.
  • model_tpm_limit: key-specific model tpm limit. Example - {"text-davinci-002": 1000, "gpt-3.5-turbo": 1000}. IF null or {} then no model specific tpm limit.
  • default_estimated_output_tokens: Proxy admin only. Expected output tokens reserved for TPM limiting when a request omits max_tokens. Positive integer. Falls back to the team setting, then to the built-in estimate.
  • default_estimated_output_tokens_per_model: Proxy admin only. Per-model override of the above. Example - {"gpt-4": 4096, "gpt-3.5-turbo": 1024}. Takes precedence over the key-wide value.
  • mcp_rpm_limit: key-specific per-MCP-server rpm limit, keyed by MCP server name (alias if set, else the configured name). Example - {"jira": 100, "slack": 200}. IF null or {} then no MCP-specific rpm limit.
  • tag_rpm_limit: key-specific per-request-tag rpm limit, keyed by request tag. Example - {"cell-1": 1000, "cell-2": 500}. Each tag gets an independent counter; requests whose tag is absent fall back to the key-level rpm limit.
  • tpm_limit_type: Type of tpm limit. Options: "best_effort_throughput" (no error if we're overallocating tpm), "guaranteed_throughput" (raise an error if we're overallocating tpm), "dynamic" (dynamically exceed limit when no 429 errors). Defaults to "best_effort_throughput".
  • rpm_limit_type: Type of rpm limit. Options: "best_effort_throughput" (no error if we're overallocating rpm), "guaranteed_throughput" (raise an error if we're overallocating rpm), "dynamic" (dynamically exceed limit when no 429 errors). Defaults to "best_effort_throughput".
  • allowed_cache_controls: List of allowed cache control values. Example - ["no-cache", "no-store"]. See all values - https://docs.spanway.ai/docs/proxy/caching#turn-on--off-caching-per-request
  • blocked: Whether the key is blocked.
  • rpm_limit: Specify rpm limit for a given key (Requests per minute)
  • tpm_limit: Specify tpm limit for a given key (Tokens per minute)
  • tpd_limit: Specify tpd limit for a given key (Tokens per day). Charged by batch submissions instead of tpm_limit/rpm_limit.
  • soft_budget: Specify soft budget for a given key. Will trigger a slack alert when this soft budget is reached.
  • tags: Tags for tracking spend and/or doing tag-based routing.
  • prompts: List of prompts that the key is allowed to use.
  • enforced_params: List of enforced params for the key (Enterprise only). Docs
  • prompts: List of prompts that the key is allowed to use.
  • allowed_routes: List of allowed routes for the key. Store the actual route or store a wildcard pattern for a set of routes. Example - ["/chat/completions", "/embeddings", "/keys/*"]
  • allowed_passthrough_routes: List of allowed pass through endpoints for the key. Store the actual endpoint or store a wildcard pattern for a set of endpoints. Example - ["/my-custom-endpoint"]. Use this instead of allowed_routes, if you just want to specify which pass through endpoints the key can access, without specifying the routes. If allowed_routes is specified, allowed_pass_through_endpoints is ignored.
  • denied_passthrough_routes: List of pass through routes the key may not call, even if allowed by allowed_passthrough_routes or allowed_routes. Matches exact paths, path prefixes, and trailing * wildcards. Applies together with the team's denied_passthrough_routes. Example - ["/my-custom-endpoint/admin"].
  • object_permission: key-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.
  • key_type: Type of key that determines default allowed routes. Options: "llm_api" (can call LLM API routes), "management" (can call management routes), "read_only" (can only call info/read routes), "default" (uses default allowed routes). Defaults to "default".
  • prompts: List of allowed prompts for the key. If specified, the key will only be able to use these specific prompts.
  • auto_rotate: Whether this key should be automatically rotated (regenerated)
  • rotation_interval: How often to auto-rotate this key (e.g., '30s', '30m', '30h', '30d'). Required if auto_rotate=True.
  • allowed_vector_store_indexes: List of allowed vector store indexes for the key. Example - [{"index_name": "my-index", "index_permissions": ["write", "read"]}]. If specified, the key will only be able to use these specific vector store indexes. Create index, using /v1/indexes endpoint.
  • router_settings: key-specific router settings. Example - {"model_group_retry_policy": {"gpt-4": {"RateLimitErrorRetries": 5}}}. IF null or {} then no router settings.
  • access_group_ids: List of access group IDs to associate with the key. Access groups define which models a key can access. Example - ["access_group_1", "access_group_2"].
  • budget_limits: List of concurrent budget windows for the key. Each window specifies a budget_limit, time_period, and optional budget_duration. Example - [{"budget_limit": 10.0, "time_period": "1d"}, {"budget_limit": 50.0, "time_period": "7d"}].

Examples:

  1. Allow users to turn on/off pii masking
curl --location 'http://0.0.0.0:4000/key/generate' --header "Authorization: Bearer $SPANWAY_MASTER_KEY" --header 'Content-Type: application/json' --data '{
"permissions": {"allow_pii_controls": true}
}'

What you get back:

  • key: The generated API key
  • expires: When the key expires.
  • user_id: Unique user id, used for tracking spend across multiple keys for the same user.

Parameters:

NameInTypeRequiredDescription
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, schema GenerateKeyRequest):

FieldTypeRequiredDescription
key_aliasstring or nullNoKey Alias
durationstring or nullNoDuration
modelsarray of any or nullNoModels
spendnumber or nullNoSpend
max_budgetnumber or nullNoMax Budget
user_idstring or nullNoUser Id
team_idstring or nullNoTeam Id
agent_idstring or nullNoAgent Id
max_parallel_requestsinteger or nullNoMost requests that may run at the same time. One more gets a 429. Empty means no cap.
metadataobject or nullNoMetadata
tpm_limitinteger or nullNoMost tokens per minute. Going over gets a 429. Empty means no cap.
rpm_limitinteger or nullNoMost requests per minute. Going over gets a 429. Empty means no cap.
budget_durationstring or nullNoBudget Duration
budget_limitsarray of BudgetLimitEntry or nullNoBudget Limits
allowed_cache_controlsarray of any or nullNoAllowed Cache Controls
configobject or nullNoConfig
permissionsobject or nullNoPermissions
model_max_budgetobject or nullNoModel Max Budget
budget_fallbacksobject or nullNoBudget Fallbacks
model_rpm_limitobject or nullNoRequests per minute for each model, as model name to a whole number
model_tpm_limitobject or nullNoTokens per minute for each model, as model name to a whole number
mcp_rpm_limitobject or nullNoMcp Rpm Limit
tag_rpm_limitobject or nullNoTag Rpm Limit
guardrailsarray of string or nullNoGuardrails
policiesarray of string or nullNoPolicies
promptsarray of string or nullNoPrompts
blockedboolean or nullNoBlocked
aliasesobject or nullNoAliases
object_permissionSpanway_ObjectPermissionBase or nullNo
keystring or nullNoKey
tpd_limitinteger or nullNoTpd Limit
default_estimated_output_tokensinteger or nullNoDefault Estimated Output Tokens
default_estimated_output_tokens_per_modelobject or nullNoDefault Estimated Output Tokens Per Model
budget_idstring or nullNoBudget Id
end_user_budget_idstring or nullNoEnd User Budget Id
tagsarray of string or nullNoTags
disable_global_guardrailsboolean or nullNoDisable Global Guardrails
enable_prompt_cachingboolean or nullNoEnable Prompt Caching
provider_preferencesobject or nullNoProvider Preferences
data_policyobject or nullNoData Policy
throttle_on_budget_exceededboolean or nullNoThrottle On Budget Exceeded
enforced_paramsarray of string or nullNoEnforced Params
allowed_routesarray of any or nullNoAllowed Routes
allowed_passthrough_routesarray of any or nullNoAllowed Passthrough Routes
denied_passthrough_routesarray of string or nullNoDenied Passthrough Routes
allowed_ipsarray of string or nullNoAllowed Ips
allowed_vector_store_indexesarray of AllowedVectorStoreIndexItem or nullNoAllowed Vector Store Indexes
rpm_limit_typeenum: "guaranteed_throughput", "best_effort_throughput", "dynamic" or nullNoguaranteed refuses limits above the team's, dynamic enforces only on model errors
tpm_limit_typeenum: "guaranteed_throughput", "best_effort_throughput", "dynamic" or nullNoguaranteed refuses limits above the team's, dynamic enforces only on model errors
router_settingsUpdateRouterConfig or nullNo
access_group_idsarray of string or nullNoAccess Group Ids
soft_budgetnumber or nullNoSoft Budget
send_invite_emailboolean or nullNoSend Invite Email
key_typeSpanwayKeyType or nullNoType of key that determines default allowed routes.
auto_rotateboolean or nullNoWhether this key should be automatically rotated
rotation_intervalstring or nullNoHow often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True
organization_idstring or nullNoOrganization Id
project_idstring or nullNoProject Id

Example request:

curl -X POST "http://localhost:4000/key/generate" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"key_alias": "billing-service",
"models": [
"claude-sonnet-5-5",
"gpt-6.1-sol"
],
"max_budget": 50,
"budget_duration": "30d",
"duration": "90d",
"rpm_limit": 120,
"metadata": {
"owner": "billing-team"
}
}'

Responses:

StatusDescriptionBody
200Successful Responseapplication/json GenerateKeyResponse
400The body breaks a key rule, for example a duration that is not valid, a taken alias or a custom key too shortapplication/json ProxyError
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not manage this key, may not create keys for that user or team, or sent a field only proxy admins may setapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
key_aliasstring or nullNoKey Alias
durationstring or nullNoDuration
modelsarray of any or nullNoModels
spendnumber or nullNoSpend
max_budgetnumber or nullNoMax Budget
user_idstring or nullNoUser Id
team_idstring or nullNoTeam Id
agent_idstring or nullNoAgent Id
max_parallel_requestsinteger or nullNoMost requests that may run at the same time. One more gets a 429. Empty means no cap.
metadataobject or nullNoMetadata
tpm_limitinteger or nullNoMost tokens per minute. Going over gets a 429. Empty means no cap.
rpm_limitinteger or nullNoMost requests per minute. Going over gets a 429. Empty means no cap.
budget_durationstring or nullNoBudget Duration
budget_limitsarray of BudgetLimitEntry or nullNoBudget Limits
allowed_cache_controlsarray of any or nullNoAllowed Cache Controls
configobject or nullNoConfig
permissionsobject or nullNoPermissions
model_max_budgetobject or nullNoModel Max Budget
budget_fallbacksobject or nullNoBudget Fallbacks
model_rpm_limitobject or nullNoRequests per minute for each model, as model name to a whole number
model_tpm_limitobject or nullNoTokens per minute for each model, as model name to a whole number
mcp_rpm_limitobject or nullNoMcp Rpm Limit
tag_rpm_limitobject or nullNoTag Rpm Limit
guardrailsarray of string or nullNoGuardrails
policiesarray of string or nullNoPolicies
promptsarray of string or nullNoPrompts
blockedboolean or nullNoBlocked
aliasesobject or nullNoAliases
object_permissionSpanway_ObjectPermissionBase or nullNo
keystringYesKey
tpd_limitinteger or nullNoTpd Limit
default_estimated_output_tokensinteger or nullNoDefault Estimated Output Tokens
default_estimated_output_tokens_per_modelobject or nullNoDefault Estimated Output Tokens Per Model
budget_idstring or nullNoBudget Id
end_user_budget_idstring or nullNoEnd User Budget Id
tagsarray of string or nullNoTags
disable_global_guardrailsboolean or nullNoDisable Global Guardrails
enable_prompt_cachingboolean or nullNoEnable Prompt Caching
provider_preferencesobject or nullNoProvider Preferences
data_policyobject or nullNoData Policy
throttle_on_budget_exceededboolean or nullNoThrottle On Budget Exceeded
enforced_paramsarray of string or nullNoEnforced Params
allowed_routesarray of any or nullNoAllowed Routes
allowed_passthrough_routesarray of any or nullNoAllowed Passthrough Routes
denied_passthrough_routesarray of string or nullNoDenied Passthrough Routes
allowed_ipsarray of string or nullNoAllowed Ips
allowed_vector_store_indexesarray of AllowedVectorStoreIndexItem or nullNoAllowed Vector Store Indexes
rpm_limit_typeenum: "guaranteed_throughput", "best_effort_throughput", "dynamic" or nullNoguaranteed refuses limits above the team's, dynamic enforces only on model errors
tpm_limit_typeenum: "guaranteed_throughput", "best_effort_throughput", "dynamic" or nullNoguaranteed refuses limits above the team's, dynamic enforces only on model errors
router_settingsUpdateRouterConfig or nullNo
access_group_idsarray of string or nullNoAccess Group Ids
key_namestring or nullNoKey Name
key_typestring or nullNoKey Type
expiresstring or nullNoExpires
token_idstring or nullNoToken Id
organization_idstring or nullNoOrganization Id
project_idstring or nullNoProject Id
spanway_budget_tableany or nullNoSpanway Budget Table
tokenstring or nullNoToken
created_bystring or nullNoCreated By
updated_bystring or nullNoUpdated By
created_atstring or nullNoCreated At
updated_atstring or nullNoUpdated At

POST /key/service-account/generate​

Create a service account key for a team

Create a key that belongs to a team instead of a person, for a service such as a nightly job. It keeps working when the person who made it leaves, and the team's limits apply to it rather than a member's. Callers who may create keys for the team may call it. The new key is shown once, and the creation is written to the audit log. Docs

Why use a service account key?

  • Prevent key from being deleted when user is deleted.
  • Apply team limits, not team member limits to key.

Docs: https://docs.spanway.ai/docs/proxy/virtual_keys

What to send:

  • duration: Specify the length of time the token is valid for. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d").
  • key_alias: User defined key alias
  • key: User defined key value. Must start with 'sk-' and be at least 16 characters long. If not set, a 16-digit unique sk-key is created for you.
  • team_id: The team id of the key
  • user_id: Ignored, because a service account key belongs to the team and not to a user.
  • budget_id: The budget id associated with the key. Created by calling /budget/new.
  • end_user_budget_id: Proxy admin only. Budget id applied to end users first seen through this key that carry no budget of their own. Omit to keep the current value, pass an empty string to clear it.
  • models: Model_name's a user is allowed to call. (if empty, key is allowed to call all models)
  • aliases: Any alias mappings, on top of anything in the config.yaml model list. - https://docs.spanway.ai/docs/proxy/virtual_keys#managing-auth---upgradedowngrade-models
  • config: any key-specific configs, overrides config in config.yaml
  • spend: Amount spent by key. Default is 0. Will be updated by proxy whenever key is used. https://docs.spanway.ai/docs/proxy/virtual_keys#managing-auth---tracking-spend
  • send_invite_email: Whether to send an invite email to the user_id, with the generate key
  • max_budget: Specify max budget for a given key.
  • budget_duration: Budget is reset at the end of specified duration. If not set, budget is never reset. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d").
  • max_parallel_requests: Rate limit a user based on the number of parallel requests. Raises 429 error, if user's parallel requests > x.
  • metadata: Metadata for key, store information for key. Example metadata = {"team": "core-infra", "app": "app2", "email": "user@example.com" }
  • guardrails: List of active guardrails for the key
  • permissions: key-specific permissions. Currently just used for turning off pii masking (if connected). Example
    • {"pii": false}
  • model_max_budget: Model-specific budgets {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}}}. IF null or {} then no model specific budget.
  • budget_fallbacks: Per-model fallback chain tried in order when that model's own model_max_budget is exceeded, e.g. {"gpt-4o": ["gpt-4o-mini"]}.
  • model_rpm_limit: key-specific model rpm limit. Example - {"text-davinci-002": 1000, "gpt-3.5-turbo": 1000}. IF null or {} then no model specific rpm limit.
  • model_tpm_limit: key-specific model tpm limit. Example - {"text-davinci-002": 1000, "gpt-3.5-turbo": 1000}. IF null or {} then no model specific tpm limit.
  • default_estimated_output_tokens: Proxy admin only. Expected output tokens reserved for TPM limiting when a request omits max_tokens. Positive integer. Falls back to the team setting, then to the built-in estimate.
  • default_estimated_output_tokens_per_model: Proxy admin only. Per-model override of the above. Example - {"gpt-4": 4096, "gpt-3.5-turbo": 1024}. Takes precedence over the key-wide value.
  • mcp_rpm_limit: key-specific per-MCP-server rpm limit, keyed by MCP server name (alias if set, else the configured name). Example - {"jira": 100, "slack": 200}. IF null or {} then no MCP-specific rpm limit.
  • tpm_limit_type: TPM rate limit type - "best_effort_throughput", "guaranteed_throughput", or "dynamic"
  • rpm_limit_type: RPM rate limit type - "best_effort_throughput", "guaranteed_throughput", or "dynamic"
  • allowed_cache_controls: List of allowed cache control values. Example - ["no-cache", "no-store"]. See all values - https://docs.spanway.ai/docs/proxy/caching#turn-on--off-caching-per-request
  • blocked: Whether the key is blocked.
  • rpm_limit: Specify rpm limit for a given key (Requests per minute)
  • tpm_limit: Specify tpm limit for a given key (Tokens per minute)
  • tpd_limit: Specify tpd limit for a given key (Tokens per day). Charged by batch submissions instead of tpm_limit/rpm_limit.
  • soft_budget: Specify soft budget for a given key. Will trigger a slack alert when this soft budget is reached.
  • tags: Tags for tracking spend and/or doing tag-based routing.
  • enforced_params: List of enforced params for the key (Enterprise only). Docs
  • allowed_routes: List of allowed routes for the key. Store the actual route or store a wildcard pattern for a set of routes. Example - ["/chat/completions", "/embeddings", "/keys/*"]
  • object_permission: key-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission. Examples:
  • allowed_vector_store_indexes: List of allowed vector store indexes for the key. Example - [{"index_name": "my-index", "index_permissions": ["write", "read"]}]. If specified, the key will only be able to use these specific vector store indexes. Create index, using /v1/indexes endpoint.
  1. Allow users to turn on/off pii masking
curl --location 'http://0.0.0.0:4000/key/generate' --header "Authorization: Bearer $SPANWAY_MASTER_KEY" --header 'Content-Type: application/json' --data '{
"permissions": {"allow_pii_controls": true}
}'

What you get back:

  • key: The generated API key
  • expires: When the key expires.
  • user_id: Unique user id, used for tracking spend across multiple keys for the same user.

Parameters:

NameInTypeRequiredDescription
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, schema GenerateKeyRequest):

FieldTypeRequiredDescription
key_aliasstring or nullNoKey Alias
durationstring or nullNoDuration
modelsarray of any or nullNoModels
spendnumber or nullNoSpend
max_budgetnumber or nullNoMax Budget
user_idstring or nullNoUser Id
team_idstring or nullNoTeam Id
agent_idstring or nullNoAgent Id
max_parallel_requestsinteger or nullNoMost requests that may run at the same time. One more gets a 429. Empty means no cap.
metadataobject or nullNoMetadata
tpm_limitinteger or nullNoMost tokens per minute. Going over gets a 429. Empty means no cap.
rpm_limitinteger or nullNoMost requests per minute. Going over gets a 429. Empty means no cap.
budget_durationstring or nullNoBudget Duration
budget_limitsarray of BudgetLimitEntry or nullNoBudget Limits
allowed_cache_controlsarray of any or nullNoAllowed Cache Controls
configobject or nullNoConfig
permissionsobject or nullNoPermissions
model_max_budgetobject or nullNoModel Max Budget
budget_fallbacksobject or nullNoBudget Fallbacks
model_rpm_limitobject or nullNoRequests per minute for each model, as model name to a whole number
model_tpm_limitobject or nullNoTokens per minute for each model, as model name to a whole number
mcp_rpm_limitobject or nullNoMcp Rpm Limit
tag_rpm_limitobject or nullNoTag Rpm Limit
guardrailsarray of string or nullNoGuardrails
policiesarray of string or nullNoPolicies
promptsarray of string or nullNoPrompts
blockedboolean or nullNoBlocked
aliasesobject or nullNoAliases
object_permissionSpanway_ObjectPermissionBase or nullNo
keystring or nullNoKey
tpd_limitinteger or nullNoTpd Limit
default_estimated_output_tokensinteger or nullNoDefault Estimated Output Tokens
default_estimated_output_tokens_per_modelobject or nullNoDefault Estimated Output Tokens Per Model
budget_idstring or nullNoBudget Id
end_user_budget_idstring or nullNoEnd User Budget Id
tagsarray of string or nullNoTags
disable_global_guardrailsboolean or nullNoDisable Global Guardrails
enable_prompt_cachingboolean or nullNoEnable Prompt Caching
provider_preferencesobject or nullNoProvider Preferences
data_policyobject or nullNoData Policy
throttle_on_budget_exceededboolean or nullNoThrottle On Budget Exceeded
enforced_paramsarray of string or nullNoEnforced Params
allowed_routesarray of any or nullNoAllowed Routes
allowed_passthrough_routesarray of any or nullNoAllowed Passthrough Routes
denied_passthrough_routesarray of string or nullNoDenied Passthrough Routes
allowed_ipsarray of string or nullNoAllowed Ips
allowed_vector_store_indexesarray of AllowedVectorStoreIndexItem or nullNoAllowed Vector Store Indexes
rpm_limit_typeenum: "guaranteed_throughput", "best_effort_throughput", "dynamic" or nullNoguaranteed refuses limits above the team's, dynamic enforces only on model errors
tpm_limit_typeenum: "guaranteed_throughput", "best_effort_throughput", "dynamic" or nullNoguaranteed refuses limits above the team's, dynamic enforces only on model errors
router_settingsUpdateRouterConfig or nullNo
access_group_idsarray of string or nullNoAccess Group Ids
soft_budgetnumber or nullNoSoft Budget
send_invite_emailboolean or nullNoSend Invite Email
key_typeSpanwayKeyType or nullNoType of key that determines default allowed routes.
auto_rotateboolean or nullNoWhether this key should be automatically rotated
rotation_intervalstring or nullNoHow often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True
organization_idstring or nullNoOrganization Id
project_idstring or nullNoProject Id

Example request:

curl -X POST "http://localhost:4000/key/service-account/generate" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"team_id": "team-ds",
"key_alias": "nightly-etl",
"models": [
"claude-haiku-5-5"
],
"max_budget": 20,
"budget_duration": "30d"
}'

Responses:

StatusDescriptionBody
200The new key, shown this onceapplication/json GenerateKeyResponse
400The body breaks a key rule, for example a duration that is not valid, a taken alias or a custom key too shortapplication/json ProxyError
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not manage this key, may not create keys for that user or team, or sent a field only proxy admins may setapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
key_aliasstring or nullNoKey Alias
durationstring or nullNoDuration
modelsarray of any or nullNoModels
spendnumber or nullNoSpend
max_budgetnumber or nullNoMax Budget
user_idstring or nullNoUser Id
team_idstring or nullNoTeam Id
agent_idstring or nullNoAgent Id
max_parallel_requestsinteger or nullNoMost requests that may run at the same time. One more gets a 429. Empty means no cap.
metadataobject or nullNoMetadata
tpm_limitinteger or nullNoMost tokens per minute. Going over gets a 429. Empty means no cap.
rpm_limitinteger or nullNoMost requests per minute. Going over gets a 429. Empty means no cap.
budget_durationstring or nullNoBudget Duration
budget_limitsarray of BudgetLimitEntry or nullNoBudget Limits
allowed_cache_controlsarray of any or nullNoAllowed Cache Controls
configobject or nullNoConfig
permissionsobject or nullNoPermissions
model_max_budgetobject or nullNoModel Max Budget
budget_fallbacksobject or nullNoBudget Fallbacks
model_rpm_limitobject or nullNoRequests per minute for each model, as model name to a whole number
model_tpm_limitobject or nullNoTokens per minute for each model, as model name to a whole number
mcp_rpm_limitobject or nullNoMcp Rpm Limit
tag_rpm_limitobject or nullNoTag Rpm Limit
guardrailsarray of string or nullNoGuardrails
policiesarray of string or nullNoPolicies
promptsarray of string or nullNoPrompts
blockedboolean or nullNoBlocked
aliasesobject or nullNoAliases
object_permissionSpanway_ObjectPermissionBase or nullNo
keystringYesKey
tpd_limitinteger or nullNoTpd Limit
default_estimated_output_tokensinteger or nullNoDefault Estimated Output Tokens
default_estimated_output_tokens_per_modelobject or nullNoDefault Estimated Output Tokens Per Model
budget_idstring or nullNoBudget Id
end_user_budget_idstring or nullNoEnd User Budget Id
tagsarray of string or nullNoTags
disable_global_guardrailsboolean or nullNoDisable Global Guardrails
enable_prompt_cachingboolean or nullNoEnable Prompt Caching
provider_preferencesobject or nullNoProvider Preferences
data_policyobject or nullNoData Policy
throttle_on_budget_exceededboolean or nullNoThrottle On Budget Exceeded
enforced_paramsarray of string or nullNoEnforced Params
allowed_routesarray of any or nullNoAllowed Routes
allowed_passthrough_routesarray of any or nullNoAllowed Passthrough Routes
denied_passthrough_routesarray of string or nullNoDenied Passthrough Routes
allowed_ipsarray of string or nullNoAllowed Ips
allowed_vector_store_indexesarray of AllowedVectorStoreIndexItem or nullNoAllowed Vector Store Indexes
rpm_limit_typeenum: "guaranteed_throughput", "best_effort_throughput", "dynamic" or nullNoguaranteed refuses limits above the team's, dynamic enforces only on model errors
tpm_limit_typeenum: "guaranteed_throughput", "best_effort_throughput", "dynamic" or nullNoguaranteed refuses limits above the team's, dynamic enforces only on model errors
router_settingsUpdateRouterConfig or nullNo
access_group_idsarray of string or nullNoAccess Group Ids
key_namestring or nullNoKey Name
key_typestring or nullNoKey Type
expiresstring or nullNoExpires
token_idstring or nullNoToken Id
organization_idstring or nullNoOrganization Id
project_idstring or nullNoProject Id
spanway_budget_tableany or nullNoSpanway Budget Table
tokenstring or nullNoToken
created_bystring or nullNoCreated By
updated_bystring or nullNoUpdated By
created_atstring or nullNoCreated At
updated_atstring or nullNoUpdated At

POST /key/update​

Update a virtual key

Change a virtual key's models, budget, limits, expiry or metadata. Proxy admins may change any key, and other callers keys they own or manage as team or organization admins. The change applies to the key's next request and the before and after are written to the audit log. Docs

The body is a merge patch: a field left out keeps its stored value, and on the key's own columns an explicit null clears it. The metadata-backed fields below are the exception, merging into the stored metadata instead: passing one as null leaves it unchanged, while metadata itself replaces the stored metadata wholesale.

What to send:

  • key: The key to update. Either key or key_alias must be provided.
  • key_alias: User-friendly key alias. If key is omitted, also identifies the key to update (must match exactly one key, same as /key/delete's key_aliases)
  • user_id: User ID associated with key
  • team_id: Team ID associated with key
  • agent_id: The agent id associated with the key.
  • project_id: Omit to retain the project, or send null to detach. A different project ID is rejected.
  • organization_id: The organization id of the key.
  • budget_id: The budget id associated with the key. Created by calling /budget/new.
  • end_user_budget_id: Proxy admin only. Budget id applied to end users first seen through this key that carry no budget of their own. Omit to keep the current value, pass an empty string to clear it.
  • allowed_ips: IP addresses or CIDR ranges the key may be used from, at most 256 entries. A request from any other client address is refused. Example - ["10.0.0.5", "10.0.0.0/8", "2001:db8::/32"]
  • data_policy: Data policy every request on the key must satisfy: require_zdr, forbid_training, restrict_code_traffic, scan_content_for_code and allowed_regions. The router drops every deployment that does not meet it. Example - {"require_zdr": true, "allowed_regions": ["eu"]}
  • models: Model_name's a user is allowed to call
  • tags: Tags for organizing keys (Enterprise only)
  • prompts: List of prompts that the key is allowed to use.
  • enforced_params: List of enforced params for the key (Enterprise only). Docs
  • spend: Amount spent by key
  • max_budget: Max budget for key
  • model_max_budget: Model-specific budgets {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}}
  • budget_fallbacks: Per-model fallback chain tried in order when that model's own model_max_budget is exceeded, e.g. {"gpt-4o": ["gpt-4o-mini"]}.
  • budget_duration: Budget reset period ("30d", "1h", etc.)
  • soft_budget: Soft budget limit (warning vs. hard stop). Will trigger a slack alert when this soft budget is reached. Set to null to remove the soft budget.
  • max_parallel_requests: Rate limit for parallel requests
  • metadata: Metadata for key. Example {"team": "core-infra", "app": "app2"}
  • tpm_limit: Tokens per minute limit
  • rpm_limit: Requests per minute limit
  • tpd_limit: Tokens per day limit, charged by batch submissions instead of tpm_limit/rpm_limit
  • model_rpm_limit: Model-specific RPM limits {"gpt-4": 100, "claude-v1": 200}
  • mcp_rpm_limit: Per-MCP-server RPM limits, keyed by MCP server name {"jira": 100, "slack": 200}
  • tag_rpm_limit: Per-request-tag RPM limits, keyed by request tag {"cell-1": 1000, "cell-2": 500}. Each tag gets an independent counter; absent tags fall back to the key-level rpm limit.
  • model_tpm_limit: Model-specific TPM limits {"gpt-4": 100000, "claude-v1": 200000}
  • default_estimated_output_tokens: Proxy admin only. Expected output tokens reserved for TPM limiting when a request omits max_tokens. Positive integer.
  • default_estimated_output_tokens_per_model: Proxy admin only. Per-model override of the above {"gpt-4": 4096, "gpt-3.5-turbo": 1024}
  • tpm_limit_type: TPM rate limit type - "best_effort_throughput", "guaranteed_throughput", or "dynamic"
  • rpm_limit_type: RPM rate limit type - "best_effort_throughput", "guaranteed_throughput", or "dynamic"
  • allowed_cache_controls: List of allowed cache control values
  • duration: Key validity duration ("30d", "1h", etc.), null to never expire, or "-1" to never expire (deprecated, use null)
  • permissions: Key-specific permissions
  • send_invite_email: Send invite email to user_id
  • guardrails: List of active guardrails for the key
  • policies: List of policy names to apply to the key. Policies define guardrails, conditions, and inheritance rules.
  • disable_global_guardrails: Whether to disable global guardrails for the key. Proxy admin only.
  • throttle_on_budget_exceeded: When the key exceeds its max_budget, throttle its tpm/rpm to the global budget_exceeded_throttle_percentage instead of blocking the key entirely.
  • enable_prompt_caching: Auto-inject prompt caching breakpoints (Anthropic cache_control markers) on requests made with this key. Supported Claude models on Anthropic, Bedrock, Vertex AI, and Azure AI only.
  • provider_preferences: Default provider preferences (order, only, ignore, sort, max_price, allow_fallbacks) for this key's chat, responses, messages, completions and embeddings requests. A request's own provider object can narrow them but never widen them. Proxy admin only. Stored in metadata.
  • prompts: List of prompts that the key is allowed to use.
  • blocked: Whether the key is blocked
  • aliases: Model aliases for the key - Docs
  • config: [DEPRECATED PARAM] Key-specific config.
  • temp_budget_increase: Temporary budget increase for the key.
  • temp_budget_expiry: Expiry time for the temporary budget increase.
  • allowed_routes: List of allowed routes for the key. Store the actual route or store a wildcard pattern for a set of routes. Example - ["/chat/completions", "/embeddings", "/keys/*"]
  • allowed_passthrough_routes: List of allowed pass through routes for the key. Store the actual route or store a wildcard pattern for a set of routes. Example - ["/my-custom-endpoint"]. Use this instead of allowed_routes, if you just want to specify which pass through routes the key can access, without specifying the routes. If allowed_routes is specified, allowed_passthrough_routes is ignored.
  • denied_passthrough_routes: List of pass through routes the key may not call, even if allowed by allowed_passthrough_routes or allowed_routes. Matches exact paths, path prefixes, and trailing * wildcards. Applies together with the team's denied_passthrough_routes. Example - ["/my-custom-endpoint/admin"].
  • prompts: List of allowed prompts for the key. If specified, the key will only be able to use these specific prompts.
  • object_permission: key-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.
  • auto_rotate: Whether this key should be automatically rotated
  • rotation_interval: How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True
  • allowed_vector_store_indexes: List of allowed vector store indexes for the key. Example - [{"index_name": "my-index", "index_permissions": ["write", "read"]}]. If specified, the key will only be able to use these specific vector store indexes. Create index, using /v1/indexes endpoint.
  • router_settings: key-specific router settings. Example - {"model_group_retry_policy": {"gpt-4": {"RateLimitErrorRetries": 5}}}. IF null or {} then no router settings.
  • access_group_ids: List of access group IDs to associate with the key. Access groups define which models a key can access. Example - ["access_group_1", "access_group_2"].
  • budget_limits: List of concurrent budget windows for the key. Each window specifies a budget_limit, time_period, and optional budget_duration. Example - [{"budget_limit": 10.0, "time_period": "1d"}, {"budget_limit": 50.0, "time_period": "7d"}].

Example:

curl --location 'http://0.0.0.0:4000/key/update' --header "Authorization: Bearer $SPANWAY_MASTER_KEY" --header 'Content-Type: application/json' --data '{
"key": "sk-<your-virtual-key>",
"key_alias": "my-key",
"user_id": "user-1234",
"team_id": "team-1234",
"max_budget": 100,
"metadata": {"any_key": "any-val"},
}'

Parameters:

NameInTypeRequiredDescription
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, schema UpdateKeyRequest):

FieldTypeRequiredDescription
key_aliasstring or nullNoKey Alias
durationstring or nullNoDuration
modelsarray of any or nullNoModels
spendnumber or nullNoSpend
max_budgetnumber or nullNoMax Budget
user_idstring or nullNoUser Id
team_idstring or nullNoTeam Id
agent_idstring or nullNoAgent Id
max_parallel_requestsinteger or nullNoMost requests that may run at the same time. One more gets a 429. Empty means no cap.
metadataobject or nullNoMetadata
tpm_limitinteger or nullNoMost tokens per minute. Going over gets a 429. Empty means no cap.
rpm_limitinteger or nullNoMost requests per minute. Going over gets a 429. Empty means no cap.
budget_durationstring or nullNoBudget Duration
budget_limitsarray of BudgetLimitEntry or nullNoBudget Limits
allowed_cache_controlsarray of any or nullNoAllowed Cache Controls
configobject or nullNoConfig
permissionsobject or nullNoPermissions
model_max_budgetobject or nullNoModel Max Budget
budget_fallbacksobject or nullNoBudget Fallbacks
model_rpm_limitobject or nullNoRequests per minute for each model, as model name to a whole number
model_tpm_limitobject or nullNoTokens per minute for each model, as model name to a whole number
mcp_rpm_limitobject or nullNoMcp Rpm Limit
tag_rpm_limitobject or nullNoTag Rpm Limit
guardrailsarray of string or nullNoGuardrails
policiesarray of string or nullNoPolicies
promptsarray of string or nullNoPrompts
blockedboolean or nullNoBlocked
aliasesobject or nullNoAliases
object_permissionSpanway_ObjectPermissionBase or nullNo
keystring or nullNoKey
tpd_limitinteger or nullNoTpd Limit
default_estimated_output_tokensinteger or nullNoDefault Estimated Output Tokens
default_estimated_output_tokens_per_modelobject or nullNoDefault Estimated Output Tokens Per Model
budget_idstring or nullNoBudget Id
end_user_budget_idstring or nullNoEnd User Budget Id
tagsarray of string or nullNoTags
disable_global_guardrailsboolean or nullNoDisable Global Guardrails
enable_prompt_cachingboolean or nullNoEnable Prompt Caching
provider_preferencesobject or nullNoProvider Preferences
data_policyobject or nullNoData Policy
throttle_on_budget_exceededboolean or nullNoThrottle On Budget Exceeded
enforced_paramsarray of string or nullNoEnforced Params
allowed_routesarray of any or nullNoAllowed Routes
allowed_passthrough_routesarray of any or nullNoAllowed Passthrough Routes
denied_passthrough_routesarray of string or nullNoDenied Passthrough Routes
allowed_ipsarray of string or nullNoAllowed Ips
allowed_vector_store_indexesarray of AllowedVectorStoreIndexItem or nullNoAllowed Vector Store Indexes
rpm_limit_typeenum: "guaranteed_throughput", "best_effort_throughput", "dynamic" or nullNoguaranteed refuses limits above the team's, dynamic enforces only on model errors
tpm_limit_typeenum: "guaranteed_throughput", "best_effort_throughput", "dynamic" or nullNoguaranteed refuses limits above the team's, dynamic enforces only on model errors
router_settingsUpdateRouterConfig or nullNo
access_group_idsarray of string or nullNoAccess Group Ids
soft_budgetnumber or nullNoSoft Budget
temp_budget_increasenumber or nullNoTemp Budget Increase
temp_budget_expirystring or nullNoTemp Budget Expiry
auto_rotateboolean or nullNoAuto Rotate
rotation_intervalstring or nullNoRotation Interval
organization_idstring or nullNoOrganization Id
project_idstring or nullNoOmit to retain the project, or send null to detach. Assigning a different project is not supported.

Example request:

curl -X POST "http://localhost:4000/key/update" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"key": "sk-...",
"max_budget": 100,
"models": [
"claude-sonnet-5-5"
]
}'

Responses:

StatusDescriptionBody
200The key and the fields that changedapplication/json object
400The body breaks a key rule, for example a duration that is not valid, a taken alias or a custom key too shortapplication/json ProxyError
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not manage this key, may not create keys for that user or team, or sent a field only proxy admins may setapplication/json ProxyError
404No key matches the key, hash or alias sentapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

POST /key/bulk_update​

Update several keys at once

Change the budget, team or tags of up to 500 keys in one call. Only proxy admins may call it. Each key is updated on its own, so one failure does not stop the others, and the answer lists which keys changed and why any failed. Each change is written to the audit log. Docs

This endpoint allows updating multiple keys in a single request. Each key update is processed independently - if some updates fail, others will still succeed.

What to send:

  • keys: List of key update requests, each containing:
    • key: The key identifier (token) to update
    • budget_id: Budget ID associated with the key
    • max_budget: Max budget for key
    • team_id: Team ID associated with key
    • tags: Tags for organizing keys
    • object_permission: key-specific object permission, as on /key/update

Only the fields an item carries are written: a field left out keeps its current value, and a field sent explicitly, null included, is applied exactly as /key/update applies it.

What you get back:

  • total_requested: Total number of keys requested for update
  • successful_updates: List of successfully updated keys with their updated info
  • failed_updates: List of failed updates with key_info and failed_reason

Example request:

curl --location 'http://0.0.0.0:4000/key/bulk_update' --header "Authorization: Bearer $SPANWAY_MASTER_KEY" --header 'Content-Type: application/json' --data '{
"keys": [
{
"key": "sk-<your-virtual-key>",
"max_budget": 100.0,
"team_id": "team-123",
"tags": ["production", "api"]
},
{
"key": "sk-5678",
"budget_id": "budget-456",
"tags": ["staging"]
}
]
}'

Parameters:

NameInTypeRequiredDescription
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, schema BulkUpdateKeyRequest):

FieldTypeRequiredDescription
keysarray of BulkUpdateKeyRequestItemYesKeys

Example request:

curl -X POST "http://localhost:4000/key/bulk_update" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"keys": [
{
"key": "sk-...",
"max_budget": 100
},
{
"key": "sk-...wxyz",
"max_budget": 100
}
]
}'

Responses:

StatusDescriptionBody
200Successful Responseapplication/json BulkUpdateKeyResponse
400The body breaks a key rule, for example a duration that is not valid, a taken alias or a custom key too shortapplication/json ProxyError
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not manage this key, may not create keys for that user or team, or sent a field only proxy admins may setapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
total_requestedintegerYesTotal Requested
successful_updatesarray of SuccessfulKeyUpdateYesSuccessful Updates
failed_updatesarray of FailedKeyUpdateYesFailed Updates

POST /team/key/bulk_update​

Update every key of a team

Apply the same change, such as a new budget, to several keys of one team or to all of them. Proxy admins and team admins with the key update permission may call it. Each key is updated on its own and failures are listed in the answer, and each change is written to the audit log. Docs

Pass team_id plus either key_ids or all_keys_in_team=True. The update_fields payload is broadcast to every selected key. Per-key failures are returned in failed_updates rather than aborting the batch.

Callable by proxy admins, or by team admins with KEY_UPDATE permission.

Parameters:

NameInTypeRequiredDescription
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, schema BulkUpdateTeamKeysRequest):

FieldTypeRequiredDescription
team_idstringYesTeam Id
key_idsarray of string or nullNoKey Ids
all_keys_in_teambooleanNoAll Keys In Team
update_fieldsKeyUpdateFieldsYesAllowlist of bulk-broadcastable fields for /team/key/bulk_update; extra="forbid" blocks RBAC/ownership/scope mutations even by team admins.

Example request:

curl -X POST "http://localhost:4000/team/key/bulk_update" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"team_id": "team-ds",
"all_keys_in_team": true,
"update_fields": {
"max_budget": 100,
"budget_duration": "30d"
}
}'

Responses:

StatusDescriptionBody
200Successful Responseapplication/json BulkUpdateKeyResponse
400The body breaks a key rule, for example a duration that is not valid, a taken alias or a custom key too shortapplication/json ProxyError
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not manage this key, may not create keys for that user or team, or sent a field only proxy admins may setapplication/json ProxyError
404No team has that idapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
total_requestedintegerYesTotal Requested
successful_updatesarray of SuccessfulKeyUpdateYesSuccessful Updates
failed_updatesarray of FailedKeyUpdateYesFailed Updates

POST /key/delete​

Delete virtual keys

Delete one or more virtual keys, so they stop working at once.

Send keys with the keys or their hashes, or key_aliases with the key aliases. Callers can only delete keys they are allowed to manage. The answer lists the deleted keys under deleted_keys.

curl -X POST 'http://localhost:4000/key/delete' \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" \
-H 'Content-Type: application/json' \
-d '{"keys": ["sk-QWrxEynunsNpV1zT48HIrw"]}'

Parameters:

NameInTypeRequiredDescription
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, schema KeyRequest):

FieldTypeRequiredDescription
keysarray of string or nullNoKeys
key_aliasesarray of string or nullNoKey Aliases

Example request:

curl -X POST "http://localhost:4000/key/delete" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"keys": [
"sk-..."
]
}'

Responses:

StatusDescriptionBody
200The keys that were deletedapplication/json DeleteKeysResponse
400Neither keys nor key_aliases were sent, or not every key could be deletedapplication/json ProxyError
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not manage this key, may not create keys for that user or team, or sent a field only proxy admins may setapplication/json ProxyError
404No key matches the key, hash or alias sentapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
deleted_keysarray of stringYesThe keys or aliases that were deleted, as they were sent

GET /key/info​

Get a key's settings and spend

Read one key's settings, spend, limits and status. Any key may read itself, and proxy admins, admin viewers and team admins may read the keys they can see. Deleted keys are still answered from the archive with status deleted. Nothing changes. Docs

What to send:

  • key: (query parameter) - The key to look up. Accepts the plaintext key or its hash; prefer the hash, since a query parameter is recorded verbatim by any HTTP access log in front of the proxy. Defaults to the key in the Authorization header.

What you get back:

  • key: The key that was looked up, echoed back as it was passed in
  • info: The key's row, minus the hashed token. Deleted keys are served from the Spanway_DeletedVerificationToken archive and carry deleted_at / deleted_by
    • status: "active" | "expired" | "revoked" | "deleted" - Derived from blocked, expires and whether the row came from the archive
    • key_alias: User-friendly key alias
    • spend: Amount spent by the key. When budget_duration is set this covers only the current budget window, not the key's lifetime
    • max_budget: Max budget for the key, enforced against spend
    • budget_duration: Budget reset period ("30d", "1h", etc.)
    • budget_reset_at: When the current budget window ends and spend is next reset to 0, not when it was last reset. Reset times snap to standard boundaries in the configured timezone (30d and 1mo land on the 1st of the month, 7d on Monday, 1h on the hour), so subtracting budget_duration from it does not give the window's start
    • model_max_budget: Per-model budgets, e.g. {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}}
    • model_max_budget_usage: Current-window spend per model, present only when the key has per-model budgets
    • budget_limits: Concurrent budget windows, exactly as stored
    • budget_limits_usage: Current-window spend per budget window, e.g. {"1h": {"current_spend": 0.0009}}, present only when the key has budget windows (read from the same cross-pod spend counter the budget enforcement uses)
    • models: Model_name's the key is allowed to call
    • tpm_limit, rpm_limit: Tokens and requests per minute limits
    • metadata: Metadata for the key, e.g. {"team": "core-infra"}
    • blocked: Whether the key is blocked
    • expires: When the key stops authenticating requests
    • last_active: When the key was last used
    • object_permission: Resolved vector store / MCP permissions when the key has an object_permission_id

Example Curl:

curl -X GET "http://0.0.0.0:4000/key/info?key=d5345c0ecc68ae6295c69f91926b2bd379e25481a40c34b5884d157a9f65d8fa" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Example Curl - if no key is passed, it will use the Key Passed in Authorization Header

curl -X GET "http://0.0.0.0:4000/key/info" -H "Authorization: Bearer sk-test-example-key-123"

Parameters:

NameInTypeRequiredDescription
keyquerystring or nullNoKey to look up. Pass the key's sha256 hash so the raw key stays out of URLs and access logs. Example key='d5345c0ecc68ae6295c69f91926b2bd379e25481a40c34b5884d157a9f65d8fa'

Example request:

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

Responses:

StatusDescriptionBody
200The key's settings, spend and statusapplication/json KeyInfoResponse
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not manage this key, may not create keys for that user or team, or sent a field only proxy admins may setapplication/json ProxyError
404No key matches the key, hash or alias sentapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
keystring or nullYesThe key or hash that was looked up, as it was sent
infoKeyInfoYesThe key's settings, spend and status

POST /key/regenerate​

Rotate a virtual key

Replace a key with a new secret value, for example when it may have leaked, keeping its settings and spend. Proxy admins may rotate any key, and other callers keys they own or manage. The old value stops working at once unless a grace period is set, the new key is shown once, and the rotation is written to the audit log. Fields sent with the request change at the same time. Regenerating the master key itself needs new_master_key: the stored secrets are re-encrypted with it (unless SPANWAY_SALT_KEY encrypts them), and the new value must be set as the master key before the next restart. Docs

What to send:

  • key: (path parameter) - The key to regenerate
  • data: Request body containing optional parameters to update
    • key: The key to regenerate.
    • new_master_key: The new master key to use, if key is the master key.
    • new_key: The new key to use, if key is not the master key. Must start with 'sk-' and be at least 16 characters long. If both set, new_master_key will be used.
    • key_alias: User-friendly key alias
    • user_id: User ID associated with key
    • team_id: Team ID associated with key
    • models: Model_name's a user is allowed to call
    • tags: Tags for organizing keys (Enterprise only)
    • spend: Amount spent by key
    • max_budget: Max budget for key
    • model_max_budget: Model-specific budgets {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}}
    • budget_fallbacks: Per-model fallback chain tried in order when that model's own model_max_budget is exceeded, e.g. {"gpt-4o": ["gpt-4o-mini"]}.
    • budget_duration: Budget reset period ("30d", "1h", etc.)
    • soft_budget: Soft budget limit (warning vs. hard stop). Will trigger a slack alert when this soft budget is reached.
    • max_parallel_requests: Rate limit for parallel requests
    • metadata: Metadata for key. Example {"team": "core-infra", "app": "app2"}
    • tpm_limit: Tokens per minute limit
    • rpm_limit: Requests per minute limit
    • model_rpm_limit: Model-specific RPM limits {"gpt-4": 100, "claude-v1": 200}
    • model_tpm_limit: Model-specific TPM limits {"gpt-4": 100000, "claude-v1": 200000}
    • allowed_cache_controls: List of allowed cache control values
    • duration: Key validity duration ("30d", "1h", etc.)
    • permissions: Key-specific permissions
    • guardrails: List of active guardrails for the key
    • blocked: Whether the key is blocked
    • grace_period: Duration to keep old key valid after rotation (e.g. "24h", "2d"). Omitted = immediate revoke. Env: SPANWAY_KEY_ROTATION_GRACE_PERIOD

What you get back:

  • The new key and its updated settings

Example:

curl --location --request POST "http://localhost:4000/key/$SPANWAY_API_KEY/regenerate" --header "Authorization: Bearer $SPANWAY_MASTER_KEY" --header 'Content-Type: application/json' --data-raw '{
"max_budget": 100,
"metadata": {"team": "core-infra"},
"models": ["gpt-4", "gpt-3.5-turbo"]
}'

Note: This is an Enterprise feature. It requires a premium license to use.

Parameters:

NameInTypeRequiredDescription
keyquerystring or nullNo
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, RegenerateKeyRequest or null):

Example request:

curl -X POST "http://localhost:4000/key/regenerate" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"key": "sk-...",
"duration": "90d"
}'

Responses:

StatusDescriptionBody
200Successful Responseapplication/json GenerateKeyResponse or null
400The body breaks a key rule, for example a duration that is not valid, or the master key is regenerated without new_master_keyapplication/json ProxyError
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not manage this key, may not create keys for that user or team, or sent a field only proxy admins may setapplication/json ProxyError
404No key matches the key, hash or alias sentapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

POST /key/{key}/regenerate​

Rotate a virtual key

Replace a key with a new secret value, for example when it may have leaked, keeping its settings and spend. Proxy admins may rotate any key, and other callers keys they own or manage. The old value stops working at once unless a grace period is set, the new key is shown once, and the rotation is written to the audit log. Fields sent with the request change at the same time. Regenerating the master key itself needs new_master_key: the stored secrets are re-encrypted with it (unless SPANWAY_SALT_KEY encrypts them), and the new value must be set as the master key before the next restart. Docs

What to send:

  • key: (path parameter) - The key to regenerate
  • data: Request body containing optional parameters to update
    • key: The key to regenerate.
    • new_master_key: The new master key to use, if key is the master key.
    • new_key: The new key to use, if key is not the master key. Must start with 'sk-' and be at least 16 characters long. If both set, new_master_key will be used.
    • key_alias: User-friendly key alias
    • user_id: User ID associated with key
    • team_id: Team ID associated with key
    • models: Model_name's a user is allowed to call
    • tags: Tags for organizing keys (Enterprise only)
    • spend: Amount spent by key
    • max_budget: Max budget for key
    • model_max_budget: Model-specific budgets {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}}
    • budget_fallbacks: Per-model fallback chain tried in order when that model's own model_max_budget is exceeded, e.g. {"gpt-4o": ["gpt-4o-mini"]}.
    • budget_duration: Budget reset period ("30d", "1h", etc.)
    • soft_budget: Soft budget limit (warning vs. hard stop). Will trigger a slack alert when this soft budget is reached.
    • max_parallel_requests: Rate limit for parallel requests
    • metadata: Metadata for key. Example {"team": "core-infra", "app": "app2"}
    • tpm_limit: Tokens per minute limit
    • rpm_limit: Requests per minute limit
    • model_rpm_limit: Model-specific RPM limits {"gpt-4": 100, "claude-v1": 200}
    • model_tpm_limit: Model-specific TPM limits {"gpt-4": 100000, "claude-v1": 200000}
    • allowed_cache_controls: List of allowed cache control values
    • duration: Key validity duration ("30d", "1h", etc.)
    • permissions: Key-specific permissions
    • guardrails: List of active guardrails for the key
    • blocked: Whether the key is blocked
    • grace_period: Duration to keep old key valid after rotation (e.g. "24h", "2d"). Omitted = immediate revoke. Env: SPANWAY_KEY_ROTATION_GRACE_PERIOD

What you get back:

  • The new key and its updated settings

Example:

curl --location --request POST "http://localhost:4000/key/$SPANWAY_API_KEY/regenerate" --header "Authorization: Bearer $SPANWAY_MASTER_KEY" --header 'Content-Type: application/json' --data-raw '{
"max_budget": 100,
"metadata": {"team": "core-infra"},
"models": ["gpt-4", "gpt-3.5-turbo"]
}'

Note: This is an Enterprise feature. It requires a premium license to use.

Parameters:

NameInTypeRequiredDescription
keypathstring or nullYes
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, RegenerateKeyRequest or null):

Example request:

curl -X POST "http://localhost:4000/key/key-123/regenerate" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"key": "sk-...",
"duration": "90d"
}'

Responses:

StatusDescriptionBody
200Successful Responseapplication/json GenerateKeyResponse or null
400The body breaks a key rule, for example a duration that is not valid, or the master key is regenerated without new_master_keyapplication/json ProxyError
401No valid key or Admin UI session was presentedapplication/json ProxyError
403The caller may not manage this key, may not create keys for that user or team, or sent a field only proxy admins may setapplication/json ProxyError
404No key matches the key, hash or alias sentapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError

POST /key/{key}/reset_spend​

Reset a key's recorded spend

Set the key's recorded spend to the amount in reset_to, usually zero, for example after a refund or a billing correction. Proxy admins, and team admins for keys of their team, may call it. The previous and new values are written to the audit log.

Parameters:

NameInTypeRequiredDescription
keypathstringYes
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, schema ResetSpendRequest):

FieldTypeRequiredDescription
reset_tonumberYesReset To

Example request:

curl -X POST "http://localhost:4000/key/key-123/reset_spend" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"reset_to": 0
}'

Responses:

StatusDescriptionBody
200The key's spend before and after the resetapplication/json ResetKeySpendResponse
400reset_to is not a number, is negative, or is above the key's current spend or budgetapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ErrorDetail
403The key's role, grants or license do not allow this actionapplication/json ErrorDetail
404No object with that id is visible to the callerapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
key_hashstringYesThe hash of the key whose spend was reset
spendnumberYesThe spend the key now has
previous_spendnumberYesThe spend the key had before the reset
max_budgetnumber or nullYesThe key's budget, unchanged by the reset
budget_reset_atstring or nullYesWhen the key's budget window next resets

GET /key/list​

List virtual keys

List the keys the caller can see, optionally for one user, team or organization, a page at a time. Proxy admins and admin viewers see every key, other callers their own keys and the keys of teams they manage. Nothing changes. Docs

What to send: expand: Expand related objects (e.g. 'user' to include user information) status: Filter by status: "active", "expired", "revoked" (blocked) or "deleted". "deleted" reads the Spanway_DeletedVerificationToken archive; the other values partition the live key table, so every live key matches exactly one of them.

Returns keys (key hashes, or full key objects when return_full_object is true), total_count, current_page and total_pages.

When expand includes "user", each key object will include a "user" field with the associated user object. Note: When expand=user is specified, full key objects are returned regardless of the return_full_object parameter.

Parameters:

NameInTypeRequiredDescription
pagequeryintegerNoPage number
sizequeryintegerNoPage size
user_idquerystring or nullNoFilter keys by user ID. Exact match by default; set substring_matching=true (admin only) for case-insensitive substring matching.
team_idquerystring or nullNoFilter keys by team ID
organization_idquerystring or nullNoFilter keys by organization ID
key_hashquerystring or nullNoFilter keys by key hash
key_aliasquerystring or nullNoFilter keys by key alias. Exact match by default; set substring_matching=true for case-insensitive substring matching.
searchquerystring or nullNoCombined search: matches keys whose token (key hash) equals the value OR whose key_alias contains it (case-insensitive).
return_full_objectquerybooleanNoReturn full key object
include_team_keysquerybooleanNoInclude all keys for teams that user is an admin of.
include_created_by_keysquerybooleanNoInclude keys created by the user
sort_byquerystring or nullNoColumn to sort by (e.g. 'user_id', 'created_at', 'spend')
sort_orderquerystringNoSort order ('asc' or 'desc')
expandqueryarray of string or nullNoExpand related objects (e.g. 'user')
statusquerystring or nullNoFilter by status: 'active' (not blocked, not expired), 'expired' (not blocked, past expiry), 'revoked' (blocked) or 'deleted' (archived keys). Omit to return live keys regardless of status.
project_idquerystring or nullNoFilter keys by project ID
access_group_idquerystring or nullNoFilter keys by access group ID
agent_idquerystring or nullNoFilter keys by agent ID
substring_matchingquerybooleanNoIf true, match key_alias (any caller) and user_id (proxy admins only) as case-insensitive substrings instead of exact values. Defaults to false: /key/list matched these exactly before substring search was added, and an e
expiresquerystring or nullNoFilter keys by expiration. 'expired' returns keys whose expires is in the past; 'active' returns keys that never expire or expire in the future. Omit to return keys regardless of expiration.

Example request:

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

Responses:

StatusDescriptionBody
200Successful Responseapplication/json KeyListResponseObject
400The request is malformed or breaks a rule named in the detailapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ErrorDetail
403The key's role, grants or license do not allow this actionapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
keysarray of string or UserAPIKeyAuth or Spanway_DeletedVerificationTokenNoKeys
total_countinteger or nullNoTotal Count
current_pageinteger or nullNoCurrent Page
total_pagesinteger or nullNoTotal Pages

GET /key/aliases​

List the key aliases the caller can see

List the aliases of the keys the caller can see, a page at a time, optionally filtered by a search text, for example to fill a key picker. Proxy admins see every alias. Nothing changes. Docs

Non-admin users only see aliases for keys they own or keys belonging to their teams.

Returns aliases with total_count, current_page, total_pages and size for paging.

Parameters:

NameInTypeRequiredDescription
pagequeryintegerNoPage number
sizequeryintegerNoPage size
searchquerystring or nullNoSearch key aliases (case-insensitive partial match)
team_idquerystring or nullNoFilter aliases to keys belonging to this team

Example request:

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

Responses:

StatusDescriptionBody
200One page of key aliasesapplication/json KeyAliasesResponse
401No valid key or Admin UI session was presentedapplication/json ErrorDetail
403The key's role, grants or license do not allow this actionapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
aliasesarray of stringYesThis page of key aliases, sorted
total_countintegerYesHow many aliases the caller can see
current_pageintegerYesThe page returned, from 1
total_pagesintegerYesHow many pages there are
sizeintegerYesAliases per page

POST /key/block​

Block a key

Stop a key from making any request until it is unblocked, for example while a leak is investigated. Proxy admins, and team or organization admins for keys they manage, may call it. Send the key or its hash. The key is refused from its next request, and the block is written to the audit log. Docs

Parameters:

NameInTypeRequiredDescription
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, schema BlockKeyRequest):

FieldTypeRequiredDescription
keystringYesKey

Example request:

curl -X POST "http://localhost:4000/key/block" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"key": "sk-..."
}'

Responses:

StatusDescriptionBody
200The key row, now blockedapplication/json Spanway_VerificationToken or null
401No valid key or Admin UI session was presentedapplication/json ErrorDetail
403The key's role, grants or license do not allow this actionapplication/json ErrorDetail
404No object with that id is visible to the callerapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError

POST /key/unblock​

Unblock a key

Let a blocked key make requests again. Proxy admins, and team or organization admins for keys they manage, may call it. Send the key or its hash. The key works from its next request, and the change is written to the audit log. Docs

Parameters:

NameInTypeRequiredDescription
spanway-changed-byheaderstring or nullNoThe spanway-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability

Request body (application/json, schema BlockKeyRequest):

FieldTypeRequiredDescription
keystringYesKey

Example request:

curl -X POST "http://localhost:4000/key/unblock" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"key": "sk-..."
}'

Responses:

StatusDescriptionBody
200The key row, unblockedapplication/json Spanway_VerificationToken
401No valid key or Admin UI session was presentedapplication/json ErrorDetail
403The key's role, grants or license do not allow this actionapplication/json ErrorDetail
404No object with that id is visible to the callerapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
tokenstring or nullNoToken
key_namestring or nullNoKey Name
key_aliasstring or nullNoKey Alias
spendnumberNoSpend
total_spendnumberNoTotal Spend
max_budgetnumber or nullNoMax Budget
expiresstring or nullNoExpires
modelsarray of anyNoModels
aliasesobjectNoAliases
configobjectNoConfig
user_idstring or nullNoUser Id
team_idstring or nullNoTeam Id
agent_idstring or nullNoAgent Id
project_idstring or nullNoProject Id
max_parallel_requestsinteger or nullNoMax Parallel Requests
metadataobjectNoMetadata
tpm_limitinteger or nullNoTpm Limit
rpm_limitinteger or nullNoRpm Limit
tpd_limitinteger or nullNoTpd Limit
budget_durationstring or nullNoBudget Duration
budget_reset_atstring or nullNoBudget Reset At
allowed_cache_controlsarray of any or nullNoAllowed Cache Controls
allowed_routesarray of any or nullNoAllowed Routes
key_typestring or nullNoKey Type
permissionsobjectNoPermissions
model_spendobjectNoModel Spend
model_max_budgetobjectNoModel Max Budget
budget_fallbacksobjectNoBudget Fallbacks
soft_budget_cooldownbooleanNoSoft Budget Cooldown
blockedboolean or nullNoBlocked
spanway_budget_tableobject or nullNoSpanway Budget Table
budget_idstring or nullNoBudget Id
org_idstring or nullNoOrg Id
created_atstring or nullNoCreated At
created_bystring or nullNoCreated By
updated_atstring or nullNoUpdated At
updated_bystring or nullNoUpdated By
settings_updated_atstring or nullNoSettings Updated At
last_activestring or nullNoLast Active
object_permission_idstring or nullNoObject Permission Id
object_permissionSpanway_ObjectPermissionTable or nullNo
access_group_idsarray of string or nullNoAccess Group Ids
rotation_countinteger or nullNoRotation Count
auto_rotateboolean or nullNoAuto Rotate
rotation_intervalstring or nullNoRotation Interval
last_rotation_atstring or nullNoLast Rotation At
key_rotation_atstring or nullNoKey Rotation At
router_settingsobject or nullNoRouter Settings
budget_limitsarray of object or nullNoBudget Limits

POST /key/health​

Check a key's logging settings

Check that the logging set up on the calling key works, by sending a test log through each of the key's logging callbacks. Any key may check itself, passed in the Authorization header. The answer says healthy or unhealthy with the callback details. Nothing changes besides the test log. Docs

Request body (application/json, object):

Example request:

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

Responses:

StatusDescriptionBody
200Successful Responseapplication/json KeyHealthResponse
400The request is malformed or breaks a rule named in the detailapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
keyenum: "healthy", "unhealthy"NoKey
logging_callbacksLoggingCallbackStatus or nullNo

GET /key/hygiene/summary​

Count the keys each hygiene finding flags

How many keys the caller can see are unused, have no budget, have no expiry date or are overdue for rotation, plus how many the auto-expiry policy would give an expiry date, and the policy in force. Counts the policy does not use are null. Proxy admins and admin viewers see every key, organization admins their organizations' keys and team admins their teams' keys. Read only, nothing changes.

Example request:

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

Responses:

StatusDescriptionBody
200Successful Responseapplication/json KeyHygieneSummary
401No valid key or Admin UI session was presentedapplication/json ErrorDetail
403The caller is not an admin of any kind, or the gateway's license does not include key_hygieneapplication/json ErrorDetail
500The key_hygiene setting in general_settings is not valid, or the gateway runs without a database and answers No database connectedapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
unusedintegerYesUnused
no_budgetintegerYesNo Budget
no_expiryintegerYesNo Expiry
rotation_overdueinteger or nullYesRotation Overdue
would_auto_expireinteger or nullYesWould Auto Expire
policyKeyHygienePolicyYes

GET /key/hygiene​

List the keys with one hygiene finding

The keys flagged with finding, with every finding each key has, ordered by hashed token. Pass the returned next_cursor as cursor for the next page. page_size is at most 200. The same visibility rules as the summary apply. Use it to find the keys to clean up, for example every key nobody used in 90 days. Read only, nothing changes.

Parameters:

NameInTypeRequiredDescription
findingqueryenum: "unused", "no_budget", "no_expiry", "rotation_overdue"Yes
page_sizequeryintegerNo
cursorquerystring or nullNo

Example request:

curl -X GET "http://localhost:4000/key/hygiene?finding=unused" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Successful Responseapplication/json KeyHygienePage
401No valid key or Admin UI session was presentedapplication/json ErrorDetail
403The caller is not an admin of any kind, or the gateway's license does not include key_hygieneapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500The key_hygiene setting in general_settings is not valid, or the gateway runs without a database and answers No database connectedapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
findingenum: "unused", "no_budget", "no_expiry", "rotation_overdue"YesFinding
rowsarray of KeyHygieneRowYesRows
next_cursorstring or nullYesNext Cursor