Skip to main content

tsurara-client

The runtime library for Python code generated by tsurara (language: python). Generated call functions pass an OperationDef to a client, which builds the request, sends it with httpx, and returns a result instead of raising. Values are converted with the TypeDefs the generator emits: records become the generated dataclasses and enums their Enum classes. It implements the runtime contract in spec/ and passes its conformance vectors. Python 3.11 or later.

Install tsurara-client[http] for the client. Without the extra, the package has no dependencies, and code generated with operations: false uses only its types layer (TypeDefs, File, MISSING); the client's names are imported on first use and need httpx.

from tsurara_client import Client, HttpError, Success, unwrap

from api import get_pet  # generated

with Client("https://api.example.com", headers={"Authorization": "Bearer ..."}, timeout=10) as client:
    match get_pet(client, pet_id=1):
        case Success(data=pet):
            print(pet.name)
        case HttpError(status=404):
            print("no such pet")
        case other:
            print("failed:", other.kind)
    pet = unwrap(get_pet(client, pet_id=1))  # raises ApiError on failure

AsyncClient takes the same options, and the same generated functions return awaitables with it:

async with AsyncClient("https://api.example.com") as client:
    pet = unwrap(await get_pet(client, pet_id=1))

Results

Class kind When
Success success A success status of the definition; data has its type
HttpError http An error status the definition documents; error has its type, documented is True
UndocumentedStatus http Any status the definition does not document, also a 2xx when other successes are documented; documented is False
NetworkFailure network Connection, DNS or TLS failures
TimeoutFailure timeout The timeout was exceeded
ParseFailure parse The body does not match the definition (Content-Type, JSON, or the type)
UnexpectedFailure unexpected A hook or converter raised, or the input cannot be sent

Cancelling an async call raises asyncio.CancelledError as usual; there is no aborted result.

Streams

A success read item by item (parseAs events, jsonLines or jsonSeq) has an iterator as data (an async iterator with AsyncClient), and the response stays open while it is read:

r = stream(client)
if isinstance(r, Success):
    with contextlib.closing(r.data) as events:  # `aclosing` with AsyncClient
        for event in events:
            ...
  • Reading to the end or closing the iterator closes the response; an iterator dropped half-read keeps its connection until it is collected.
  • timeout covers connecting and the response headers, not the wait for the next item.
  • Invalid JSON in an item raises ValueError from the iteration, and a broken connection raises httpx's error, since the Result was already returned.

Options

Option Description
headers Headers for every request, or a function of the request info returning them (async with AsyncClient)
timeout Seconds, for each request; per call with timeout=
http The httpx.Client / httpx.AsyncClient to send with: proxies, transports (retries), event hooks, tests with httpx.MockTransport. The client closes only the one it made
on_result Observes every result
on_undocumented_status Observes responses whose status the definition does not document, to notice drift between the server and the definition
auth auth(scheme, info) returns the credential for a security scheme of the operation (scheme.scheme is its name; generated SecuritySchemeName lists them), or None. API keys go in their header, query or cookie, bearer and OAuth tokens in Authorization: Bearer, basic credentials (user:password) in Authorization: Basic
retry Retry() retries network failures and 408, 429, 500, 502, 503 and 504 for idempotent methods, up to 2 times, honoring Retry-After and otherwise backing off with jitter; timeout covers all attempts

Hooks never change the result; their exceptions are ignored.

Values

  • MISSING marks a field absent from JSON, as opposed to None (null); only fields that are both optional and nullable use it.
  • Unlisted values of open enums and open tagged unions stay as their JSON values (Status | str).
  • Binary values are bytes, or File(content, filename=..., content_type=...) when a multipart part or body needs a name or media type. Binary responses are bytes.
  • External types (x-tsurara-type) are converted by converters registered by name: TypeDefs.with_converters({"Uuid": UuidConverter()}).

Testing without a server

tsurara_client.testing.MockRouter is an httpx mock handler that answers from handlers routed by operation (spec/README.md, Mock transports), for Client and AsyncClient:

import httpx
from tsurara_client import Client
from tsurara_client.testing import MockResponse, MockRouter

from api.operations.get_pet import DEF as GET_PET  # generated

router = MockRouter(base_path="/v1")
router.add(GET_PET, lambda req: MockResponse(200, json={"id": int(req.params["pet_id"]), "name": "Pochi"}))
client = Client("https://api.test/v1", http=httpx.Client(transport=httpx.MockTransport(router)))
# ... call generated functions, then inspect router.calls

router.route(method, path, handler) adds a route without an OperationDef. A handler that raises, and a request no route matches, are NetworkFailures; with MockRouter(unmatched="record"), unmatched requests are answered with 501 and kept in router.unmatched.

Development

uv sync --project runtimes/python
uv run --directory runtimes/python pytest
node_modules/.bin/pyright -p runtimes/python

Metadata

Release files for tsurara-client 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tsurara-client 0.1.1
File Size Uploaded Provenance Actions
tsurara_client-0.1.1.tar.gz 36.9 kB Without provenance Details for tsurara_client-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tsurara-client 0.1.1
File Interpreter ABI Platform Actions
tsurara_client-0.1.1-py3-none-any.whl Python 3 none any Details for tsurara_client-0.1.1-py3-none-any.whl

Total release size: 68.3 kB

Release files / tsurara_client-0.1.1.tar.gz

Download URL tsurara_client-0.1.1.tar.gz
Size 36.9 kB
Tags Source
SHA-256 checksum
How to use checksums
48bb5c8ee38f4c704648ac242bdf9fd25a748943bd8a4b03c864333e6e45a1d8
BLAKE2b-256 checksum
How to use checksums
ef5897267c33782efc573e43c01fa808beb37a78141b9b4fd11b4635de155929
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / tsurara_client-0.1.1-py3-none-any.whl

Download URL tsurara_client-0.1.1-py3-none-any.whl
Size 31.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8d534708a707ac62ce0f57b97ac0b4bf9c55754ba07ad030d58dadcd74bf9053
BLAKE2b-256 checksum
How to use checksums
e591e1352359fc5dc3dc2a8bec35efa3abb0019458e614cc687e7edcff19df60
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for tsurara-client 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page