Metadata-Version: 2.5
Name: status302
Version: 1.5.0
Summary: Official Python SDK for the Status302 API: typed REST client, realtime stream client and webhook verification.
Project-URL: Homepage, https://status302.com
Project-URL: Documentation, https://status302.com/docs/sdks/python/
Author: Status302
License-Expression: MIT
Keywords: api,market data,status302,tickets,websocket
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27
Requires-Dist: msgpack>=1.0
Requires-Dist: websockets>=13
Description-Content-Type: text/markdown

# status302 — Python SDK

Official Python client for the [Status302 API](https://status302.com/docs/): real-time ticket market data (catalog, metrics, sales, seat maps) over REST, a realtime WebSocket stream and signed webhooks.

- Typed methods for every public operation (`TypedDict` models generated from the public OpenAPI spec)
- Blocking `Status302` and asyncio `AsyncStatus302` clients on [httpx](https://www.python-httpx.org/)
- Automatic retries on `429` and `5xx` (idempotent requests) honouring `Retry-After`
- Pagination helpers (cursors and alert `nextBefore` ids) and typed errors (`PlanRequiredError`, `RateLimitError`, …) carrying the response's `request_id` (also appended to the message as `(request <id>)`; quote it to support)
- Conditional requests: `if_none_match` with a typed `NotModified` result, response ETags, and an opt-in ETag cache
- Stream client: bearer or ticket auth, reconnects with backoff, `since` resume per topic, resync notices, seq deduplication
- Webhook signature verification

The package version equals the version of the public API spec it was generated from.

## Install

```sh
pip install status302        # or: uv add status302
```

Python ≥ 3.11.

## Quickstart

```python
import os
from status302 import Status302

with Status302(api_key=os.environ["STATUS302_API_KEY"]) as status302:
    page = status302.list_events(country="US", limit=5)
    for event in page["items"]:
        print(event["id"], event["name"], event["startsAt"])

    metrics = status302.get_event_metrics(page["items"][0]["id"])
    for row in metrics["items"]:
        print(row["scope"], row["floor"], row["currency"])  # money is integer minor units
```

Create an API key in the app under **Settings → Developers**. Keys look like `tx_live_<keyId>_<secret>` and are sent as `Authorization: Bearer …`.

### Pagination

```python
for event in status302.paginate(status302.list_events, country="US", limit=200):
    ...
```

`pages(...)` yields whole pages instead. Both follow `nextCursor` until it is null, or `nextBefore` (as `before`) for `list_alert_rules` and `list_alert_events`.

### Conditional requests

```python
from status302 import MemoryETagCache, NotModified, Status302

first = status302.with_response.get_event_metrics(4102)          # APIResponse with .data, .etag, .status, .rate_limit
nxt = status302.get_event_metrics(4102, if_none_match=first.etag)  # types.EventMetricsList | NotModified
if isinstance(nxt, NotModified):
    print("unchanged since", nxt.etag)

cached = Status302(api_key=os.environ["STATUS302_API_KEY"], etag_cache=MemoryETagCache())
```

Operations that accept `If-None-Match` take `if_none_match`; a `304` returns `NotModified` instead of raising, and the return type includes it only when the argument is passed. `with_response` has every operation returning the whole `APIResponse`. With `etag_cache` the client revalidates every `GET` by itself and returns the stored body on `304`; `MemoryETagCache(max_entries=1000)` is thread-safe and LRU, and any object with `get`/`set` (the `ETagCache` protocol) works.

### Errors and rate limits

```python
from status302 import PlanRequiredError, RateLimitError

try:
    status302.list_movers(window="24h")
except PlanRequiredError as e:
    print("needs plan", e.required_plan)
except RateLimitError as e:
    print("retry in", e.retry_after, "s; quota:", e.rate_limit)
```

`429` responses are retried after `Retry-After` (up to `max_retry_after`, default 60 s); `5xx` and connection errors are retried for idempotent methods with exponential backoff (`max_retries`, default 3). `status302.request(...)` returns the body together with status, headers, ETag and the parsed `RateLimit` state.

### Realtime stream

```python
import asyncio, os
from status302 import AsyncStatus302, DataMessage, ResyncMessage

async def main() -> None:
    async with AsyncStatus302(api_key=os.environ["STATUS302_API_KEY"]) as status302:
        async with status302.stream() as stream:
            stream.subscribe("sales", filter={"country": ["US"]})
            async for message in stream:
                if isinstance(message, DataMessage):
                    print(message.seq, message.data)
                elif isinstance(message, ResyncMessage):
                    snapshot = await stream.fetch_snapshot(message)

asyncio.run(main())
```

The key needs the `stream` scope to connect, and each topic the scope of its REST equivalent (`event.{id}.kpis` → `market:read`, `sales`/`event.{id}.sales` → `sales:read`, `event.{id}.primary` → `maps:read` or `market:read`, `onsales` → `catalog:read`, `alerts` → `alerts:write`); without it the subscription fails with a `forbidden_topic` `SubscriptionError`. Server-side code authenticates with the key on the upgrade request (`auth="bearer"`, default with a key); pass `auth="ticket"` and `get_ticket=` to connect with single-use tickets instead (same scopes as the key).

#### Binary encoding (MessagePack)

`stream(encoding="msgpack")` asks the server for binary MessagePack frames (`encoding=msgpack` on the URL) instead of JSON text. Messages and `data` payloads decode to the same values as with JSON, so iteration doesn't change; the client's own messages stay JSON. Default: `"json"`.

### Webhooks

```python
from status302 import verify_webhook, WebhookVerificationError

event = verify_webhook(raw_body, headers["Status302-Signature"], os.environ["STATUS302_WEBHOOK_SECRET"])
```

## Versioning

Releases share the version of the API spec they were generated from (`status302.__version__`); `/v1` changes are additive only, so new fields, operations and enum values arrive in minor releases. See the [changelog](https://status302.com/docs/changelog/).

## License

MIT
