Python client
spanway-client is a typed Python client for the gateway's management API and its OpenAI-compatible inference routes. Its request and response models are frozen Pydantic v2 classes generated from the gateway's OpenAPI document, the same document the TypeScript client is generated from, so every field name, enum and required property matches the gateway version the package was built for.
The client is not published to a package index. Each release attaches it to the release page as spanway_client-<version>-py3-none-any.whl and spanway_client-<version>.tar.gz, listed in SHA256SUMS and each signed with cosign, so download the files for the gateway version you run from the location in your onboarding pack, check them as described in release assets, and install the one you verified into your application's environment.
pip install ./spanway_client-2.0.0-py3-none-any.whl
The package needs Python 3.11 or newer and depends only on httpx, pydantic and typing-extensions. Its version always equals the gateway version it was generated from.
A real-world scenario
A platform team creates a team and a scoped key for every new project by hand in the Admin UI, and mistakes creep in. They write a short onboarding script with the Python client instead. A typo in a field name now fails when the model is built, and a refused call comes back as a value the script can report instead of a stack trace.
Steps
-
Download the wheel for your gateway version from the release page, check it against
SHA256SUMS, and install the verified file as shown above. -
Check that the key you will use works.
keys.info(key)reads the same route with?key=set, and without it the gateway answers for the key that made the call.curl http://localhost:4000/key/info -H "Authorization: Bearer $SPANWAY_API_KEY" -
Write the script from the team and key example in Examples and run it.
-
Open Teams and then Virtual Keys in the Admin UI and check that the new team and its key are listed.
Expected result
The script prints the new key. The team shows on the Teams page with its budget, and the key shows on Virtual Keys with the team and model you gave it.
Connecting
import httpx
from spanway_client import SpanwayClient
with httpx.Client(timeout=30) as http:
spanway = SpanwayClient(base_url="https://gateway.example.com", api_key="sk-...", http=http)
api_key is a virtual key or the master key and is sent as Authorization: Bearer <key> on every request. A call only reaches what the key is allowed to manage, so a team admin key manages its own team while the master key manages everything. The client never creates its own HTTP connection pool. You pass in an httpx.Client, which is where proxies, custom CA bundles, timeouts and retries are configured, and which you close when you are done. AsyncSpanwayClient takes an httpx.AsyncClient and has the same methods as coroutines. The key is kept out of the client's repr, so logging the client object does not print it.
Endpoints and results
Each surface is a module of endpoint builders. A builder takes the request body as a generated model, or the identifiers and filters as arguments, and returns an Endpoint that describes one call. send runs it.
from spanway_client import HttpError, Ok, keys
from spanway_client.schema import GenerateKeyRequest
result = spanway.send(keys.generate(GenerateKeyRequest(key_alias="platform-ci", models=["claude-sonnet-5-5"])))
match result:
case Ok(value=created):
print(created.key, created.expires)
case HttpError(status=403, detail=detail):
print("the key cannot create keys", detail)
case _:
print(result)
send never raises for a failed call. It returns one of five values.
| Result | When | Fields |
|---|---|---|
Ok | 2xx response whose body matches the schema | value, the decoded model, and status |
InvalidRequest | a path identifier is empty, . or .., or contains / or \, so the request was never sent | method, path and reason, which names the parameter but not its value |
HttpError | any non-2xx response | method, path, status and detail, the gateway's JSON error body or its text |
TransportError | the request never got a response, such as a refused connection or a timeout | method, path and reason, the httpx error class name |
DecodeError | 2xx response whose body does not match the generated model | method, path, status and reason, the failing field locations |
unwrap(result) returns the value of an Ok and raises SpanwayRequestError, SpanwayHTTPError, SpanwayTransportError or SpanwayDecodeError for the others, each carrying the original value as .error, for code that prefers exceptions. A TransportError reason is the error class name only and a DecodeError reason lists the field locations without their values, so neither repeats a key that appeared in the URL or the response.
Request models are serialized with only the fields you set, so an update never sends null for a field you left out. Response models keep fields a newer gateway added, readable through model_extra, while a field whose type changed comes back as a DecodeError naming the field. Path identifiers are percent-encoded, and one that could leave its path segment, such as .. or ../user/delete, is refused as an InvalidRequest before anything is sent. Every generated model, including the single-value root models such as MaxBudget, is frozen.
Surfaces
| Module | Builders | License |
|---|---|---|
keys | generate, info, list, update, delete, block, unblock, regenerate, and next_page for paging | Starter |
teams | create, info, list, update, delete, block, unblock, add_member, update_member, remove_member, add_model, remove_model | Starter |
users | create, info, list, update, delete, and next_page | Starter |
organizations | create, info, list, delete, add_member, update_member, remove_member | Starter |
models | create, info, update, patch, delete | Starter |
budgets | create, info, list, settings, update, delete | Starter |
guardrails | create, list, info, update, patch, delete, apply | Starter |
mcp_servers | create, list, info, update, delete, health, tools | Starter |
agents | create, list, info, update, delete, make_public, set_public, kill_switch, identity, discover, daily_activity | Starter, kill_switch and identity need agent_governance |
custom_agents | create, list, info, update, delete, run, runs, run_info, cancel_run | Enterprise, needs custom_agents |
evals | Datasets: create_dataset, import_dataset, list_datasets, get_dataset, update_dataset, delete_dataset, list_dataset_versions, get_dataset_version, delete_dataset_version, dataset_from_sessions, preview_sessions. Runs: create_run, list_runs, get_run, run_results, run_result, run_items, submit_run_outputs, finish_run, run_verdict, compare_runs, playground, cancel_run, delete_run. Feedback: submit_feedback, list_feedback, delete_feedback. Scorers: scorers, dry_run_scorer, create_remote_scorer, list_remote_scorers, get_remote_scorer, update_remote_scorer, delete_remote_scorer, rotate_remote_scorer_secret. Online scoring: create_online_rule, list_online_rules, get_online_rule, update_online_rule, delete_online_rule, online_scores, online_summary. Red teaming: red_team_catalogue, create_red_team_run, list_red_team_runs, get_red_team_run, red_team_results, cancel_red_team_run, delete_red_team_run. Paging: next_page. Schedules, shadow results and review queues: dataset_from_logs, preview_logs, create_schedule, list_schedules, get_schedule, update_schedule, delete_schedule, run_schedule_now, list_shadow_results, create_review_queue, list_review_queues, get_review_queue, update_review_queue, delete_review_queue, enqueue_from_run, enqueue_from_logs, enqueue_from_shadow, review_items, review_item, delete_review_item, review_calibration, review_queue_to_dataset, assigned_review_queues, next_review_item, reviewer_item, label_review_item, skip_review_item | Enterprise, needs evals |
cloud | signup, verify, resend, plans, subscribe, portal, import_config, tenant, update_tenant, cancel_tenant, export_tenant, list_credits, purchase_credits, auto_topup, set_auto_topup, disable_auto_topup, credentials, add_credential, delete_credential, list_tenants, get_tenant, change_plan, suspend_tenant, reinstate_tenant, next_credits_page and next_tenant_page | Spanway Cloud, needs cloud |
billing | create_account, update_account, delete_account, account, list_accounts, suspend_account, reinstate_account, usage, generate_invoice, generate_all_invoices, issue_invoice, mark_invoice_paid, void_invoice, invoice, list_invoices, next_account_page and next_invoice_page. The CSV export of an invoice is reached through an Endpoint you describe yourself, as shown under examples | Enterprise, needs billing |
chat | completions | Starter |
responses | create | Starter |
embeddings | create | Starter |
rerank | create | Starter |
A builder for a licensed route returns an HttpError with status 403 when the gateway's license does not include that feature, and the detail names the feature. The package itself is the same for every gateway.
Five inference routes have a TypeScript helper but no Python builder, POST /v1/messages, POST /v1/moderations, POST /v1/images/generations, POST /v1/audio/speech and POST /v1/audio/transcriptions. Call them from Python with an Endpoint you describe yourself, as shown under examples. Every other route a TypeScript helper calls has a Python builder, and a test fails the build if a TypeScript helper gains a route the Python package does not have.
Where the OpenAPI document names a response model the builder returns it, and where the gateway documents the response as free-form JSON the builder returns pydantic.JsonValue. The inference builders take the OpenAI request body as a dictionary and always ask for a non-streamed response. For streaming, use the OpenAI SDK pointed at the gateway with stream=True, as described on chat completions, or the TypeScript client, whose stream helpers yield typed events.
Pagination
pages walks a paged list. It takes a function from page number to endpoint and a function that reads the next page number from a response, yields one result per page, and stops after the last page, after the first failed result, or when the gateway does not advance the page.
from spanway_client import Ok, keys
for page in spanway.pages(lambda number: keys.list(number, 100, team_id="team-platform"), keys.next_page):
match page:
case Ok(value=listing):
for key in listing.keys or []:
print(key)
case _:
print("stopped:", page)
On AsyncSpanwayClient, pages is an async iterator used with async for.
Examples
Create a team with a monthly budget and a key scoped to it.
from spanway_client import keys, teams, unwrap
from spanway_client.schema import GenerateKeyRequest, NewTeamRequest
team = unwrap(spanway.send(teams.create(NewTeamRequest(team_alias="platform", max_budget=500, budget_duration="30d"))))
key = unwrap(
spanway.send(
keys.generate(
GenerateKeyRequest(key_alias="platform-ci", team_id=team.team_id, models=["claude-sonnet-5-5"], duration="30d")
)
)
)
print(key.key)
Start an eval run and read the failures.
from spanway_client import evals, unwrap
from spanway_client.schema import NewEvalRun
run = unwrap(spanway.send(evals.create_run(NewEvalRun.model_validate({
"dataset_id": "dataset-golden",
"models": ["claude-sonnet-5-5", "claude-haiku-5-5"],
"scorer": {"type": "exact_match"},
}))))
failures = unwrap(spanway.send(evals.run_results(run.run_id, passed=False)))
Call an endpoint with no builder by describing it yourself. The same auth header, error values and decoding apply.
from spanway_client import Endpoint
from spanway_client.endpoint import JSON
readiness = spanway.send(Endpoint("GET", "/health/readiness", JSON))
Run the same calls from async code.
import asyncio
import httpx
from spanway_client import AsyncSpanwayClient, keys, unwrap
async def main() -> None:
async with httpx.AsyncClient(timeout=30) as http:
spanway = AsyncSpanwayClient(base_url="https://gateway.example.com", api_key="sk-...", http=http)
listing = unwrap(await spanway.send(keys.list(size=50)))
print(listing.total_count)
asyncio.run(main())
Running evals from pytest
The client carries a pytest plugin, so a test can start a gateway eval run and fail when the gateway's verdict is failed. Installing the wheel registers the plugin, and a test asks for the spanway_evals fixture.
from spanway_client.schema import EvalGate, NewEvalRun
def test_support_bot_refunds(spanway_evals):
spanway_evals.gate(
NewEvalRun(
dataset_name="support-golden",
models=["gpt-5.5"],
scorer={"type": "exact_match"},
baseline_key="support-bot",
gate=EvalGate(min_pass_rate=0.85, max_pass_rate_drop=0.03),
)
)
The plugin reads SPANWAY_PROXY_URL and SPANWAY_PROXY_API_KEY, marks eval tests spanway_eval and, in CI, sends the job's git context so a pull request is compared with your main branch. Evals as code covers every setting and a CI workflow.
Keeping the models current
The models are generated from the gateway's OpenAPI document for each release, so the client version always equals the gateway version and its models match every route and field of that release. Upgrade the client together with the gateway. Each release attaches the client's two files to the release page, signed with cosign and with an SPDX SBOM, as described in release assets. No release publishes the client to a package index, so the release page is the only place it comes from.
License
The package ships under the Spanway Client License in its LICENSE file, the same terms as the TypeScript client. You may use and modify it in production to call a Spanway gateway you are allowed to use, and redistribute it, changed or not, as part of software that calls a Spanway gateway, as long as the notice stays with it. Selling it on its own or using it to build a competing gateway is not allowed. The gateway itself is licensed separately.
The CLI's client
The CLI spanwayctl ships inside the gateway image. Use spanway-client for your own code.
For TypeScript, see the TypeScript client. For exploring the API interactively, see the Postman collection.
Errors
| Result | Typical cause | Fix |
|---|---|---|
HttpError(status=401) | The key is wrong, deleted or expired. | Use a valid key, see error reference. |
HttpError(status=403) | The key may not manage that object, or the route needs a license feature, named in detail. | Use a key with the right role, or add the feature. |
HttpError(status=422) | A field failed the gateway's validation. detail names it. | Fix the field. |
TransportError | The gateway could not be reached, or the request timed out. | Check base_url, the network and the httpx timeout. |
DecodeError | The gateway is a different version than the client. | Install the client of the same version as the gateway. |
InvalidRequest | A path identifier was empty, was . or .., or contained / or \. The reason reads path parameter <name> cannot be empty, '.' or '..', or contain / or \. | Pass the real id. |
Logs
The client writes no log of its own. Every call it makes is an ordinary gateway request, so it shows up on Logs (/ui/logs) under the key you passed, and a call that changes something, such as keys.generate or teams.update, also writes a row to the audit log with the key's user as the actor. The gateway's own log lines for those requests are in the log reference. To see what the client sent, turn on httpx logging in your program with logging.getLogger("httpx").setLevel(logging.INFO), which prints the method, URL and status of each call but not the key.
Related
- TypeScript client for the same API from TypeScript.
- Developer CLI for the command line.
- Error reference for every error status.
- Evals as code for the pytest plugin.