Metadata-Version: 2.5
Name: tsurara-client
Version: 0.1.2
Summary: Runtime library for Python code generated by tsurara
Project-URL: Repository, https://github.com/tsurara-openapi/tsurara
License-Expression: MIT
License-File: LICENSE
Requires-Python: >=3.11
Provides-Extra: http
Requires-Dist: httpx>=0.27; extra == 'http'
Description-Content-Type: text/markdown

# 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](https://www.python-httpx.org/), 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.

```python
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:

```python
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:

```python
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`:

```python
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 `NetworkFailure`s; with `MockRouter(unmatched="record")`, unmatched requests are answered with 501 and kept in `router.unmatched`.

## Development

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