Skip to main content

Calling the gateway

Once an admin has issued you a virtual key, you call the gateway exactly like the provider APIs you already know. All you need is the gateway's base URL and that key, whether the gateway is one your company runs or a Spanway Cloud workspace, where the base URL is shown in the workspace, such as https://api.spanway.ai. The gateway accepts OpenAI-style requests on /v1/chat/completions, /v1/responses and the other OpenAI routes, Anthropic-style requests on /v1/messages, and Google-style requests on the Gemini routes. Use the public model_name your admin registered, not the upstream provider model id. Provider credentials stay in the gateway, so an application never holds one.

When you would use this​

Your team's release notes tool already uses the OpenAI Python SDK against a provider directly. You point its base_url at the gateway, swap the provider key for your virtual key, and leave the rest of the code alone. Requests now go through the gateway, spend lands on your key, the model list your admin set applies, and switching the tool to a different provider's model later is a one word change in the request.

Before you start​

Ask an admin for a key, or create your own on the Virtual Keys page of the Admin UI with + Create New Key, see virtual keys. Export it as SPANWAY_API_KEY. GET /v1/models with the key lists the models you may call.

Step by step​

  1. Try the key with curl. The Playground page of the Admin UI sends the same request from the browser.

    curl -X POST http://localhost:4000/v1/chat/completions \
    -H "Authorization: Bearer $SPANWAY_API_KEY" \
    -H "Content-Type: application/json" \
    -H "x-spanway-tags: checkout,experiment-b" \
    -d '{"model": "claude-sonnet-5-5", "messages": [{"role": "user", "content": "Hello"}]}'
  2. Point an OpenAI SDK at the gateway. Only base_url and api_key change.

    import os
    from openai import OpenAI

    client = OpenAI(base_url="http://localhost:4000", api_key=os.environ["SPANWAY_API_KEY"])
    response = client.chat.completions.create(
    model="claude-sonnet-5-5",
    messages=[{"role": "user", "content": "Draft a release note title."}],
    user="customer-42",
    extra_body={"metadata": {"feature": "release-notes"}},
    )
    print(response.choices[0].message.content)

    The user field identifies your end user, which lets the gateway track spend and apply budgets per customer. Anything under metadata is stored with the request in the spend logs and passed to logging integrations.

  3. Or point an Anthropic SDK at it. The /v1/messages route works for non-Anthropic models too, because the gateway translates the request, see Anthropic Messages.

    import os
    import anthropic

    client = anthropic.Anthropic(base_url="http://localhost:4000", api_key=os.environ["SPANWAY_API_KEY"])
    message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=512,
    messages=[{"role": "user", "content": "Explain retries in one paragraph."}],
    )
    print(message.content[0].text)
  4. Or use the Responses API. /v1/responses accepts the OpenAI Responses API for every model the key allows, see Responses API.

    import os
    from openai import OpenAI

    client = OpenAI(base_url="http://localhost:4000", api_key=os.environ["SPANWAY_API_KEY"])
    response = client.responses.create(
    model="gpt-6.1-sol",
    input="Summarise the last release in two sentences.",
    )
    print(response.output_text)
  5. Check your own key. Open Virtual Keys in the Admin UI and click your key to see its spend, budget and models, or call GET /key/info with your own key, which returns its budget, spend, limits and allowed models.

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

What you should see​

A 200 response in the provider's own format, with the model name you sent and the usual usage block. The response headers carry x-spanway-call-id, the request's id in the spend logs, and x-spanway-response-cost, what the call cost in US dollars. The Logs page of the Admin UI shows the request a few seconds later under your key, and the key's spend grows by the cost.

Authenticating​

Send the key as a bearer token. The gateway also accepts it in the headers that provider SDKs use, so most clients work without changes.

HeaderTypical client
Authorization: Bearer sk-...OpenAI SDKs, curl, most HTTP clients
x-api-key: sk-...Anthropic SDKs
x-goog-api-key: sk-...Google AI Studio clients
API-Key: sk-...Older Azure OpenAI clients
x-spanway-api-key: sk-... or x-spanway-api-key: Bearer sk-...Any client that needs Authorization for something else, such as an MCP client that signs in with OAuth
Ocp-Apim-Subscription-Key: sk-...Clients built for Azure API Management
?key=sk-... query parameterGoogle AI Studio clients, accepted on the generateContent routes only

When a request carries more than one of these, x-spanway-api-key wins, then Authorization, then API-Key, x-api-key, x-goog-api-key, Ocp-Apim-Subscription-Key and last the key query parameter. An admin can also set general_settings.spanway_key_header_name to read the key from a header of your choice. Connect any client lists the base URL and header each kind of client needs.

Request headers the gateway reads​

HeaderEffect
x-spanway-tagsComma separated tags recorded with the request and used by tag routing.
x-spanway-session-idGroups related requests into one session for logs and session affinity.
x-spanway-trace-idCorrelates the request with your own tracing.
x-spanway-timeout, x-spanway-stream-timeoutPer-request timeouts in seconds.
x-spanway-num-retriesPer-request retry count.
x-spanway-priorityRequest priority for queued scheduling.
x-spanway-cache-keyExplicit cache key, see caching.
x-spanway-spend-logs-metadataJSON object merged into the spend log metadata.
x-spanway-routing-skipstrue to get the skipped candidate deployments and their reasons back in the x-spanway-routing-skips response header, see routing decision headers.

Response headers the gateway returns​

Every response carries headers you can log on the client side to tie a request to the gateway's records.

HeaderMeaning
x-spanway-call-idUnique id of the request, also stored in the spend logs.
x-spanway-model-id, x-spanway-model-groupDeployment and model group that served the call.
x-spanway-response-costCost of the call in US dollars.
x-spanway-attempted-fallbacksNumber of fallbacks tried before success.
x-spanway-response-duration-msTotal time spent in the gateway and provider.
x-spanway-versionGateway version.
x-spanway-routing-reason, x-spanway-attemptsWhy the request was routed where it was and how many provider calls it took. Routing decision headers lists every routing header and the opt-in x-spanway-routing-skips.

Errors​

ErrorCauseFix
401 Authentication Error, Invalid proxy server token passedThe key is wrong or deleted, or sent in a header the gateway does not read.Check the value and the header.
401 Authentication Error, Key is blocked. Update via /key/unblock if you're an admin.An admin blocked your key.Ask your admin to unblock it, or for a new key.
401 with expired in the messageThe key passed its expiry date.Ask your admin to regenerate it.
403 The requested model '<model>' is not available for this API key, or the model name is invalid.The model is not on your key's or team's list.Call GET /v1/models with your key and use one of those names.
422 Budget has been exceeded!Your key, team or user budget is spent.Wait for the reset, or ask your admin to raise the budget. An admin can set budget_exceeded_status_code: 429 to answer 429 instead.
429 with a rate limit messageYour key's requests or tokens per minute, or the team's, are used up.Slow down, or ask for a higher limit.
400 Invalid model name passed in model=...No deployment on the gateway has that public name.Use a name from GET /v1/models.
503 when a budget or rate limit cannot be checkedThe gateway cannot reach Redis or its database and refuses to admit requests it cannot count.Retry shortly. The admin page Redis requirements explains the setting.

Logs​

Your own calls never write your key or your prompt to the gateway log. When a call is refused, the gateway admin sees one line for it, which helps when you report a problem.

LevelLineMeaningAction
WARNINGspanway.proxy.proxy_server.user_api_key_auth(): Exception occured - <error> Requester IP Address:<ip>The key does not start with sk-, for example a provider key was sent by mistake.Send your Spanway virtual key instead.
ERRORThe same line with Invalid proxy server token passed, Key is blocked or expiredThe key is unknown, blocked or expired.Give your admin the time of the call and the x-spanway-call-id of a working call, never the key itself.

The full list is in the log reference, and the admin's view of the key lines is under virtual key lines.