Metadata-Version: 2.5
Name: punchrelay
Version: 0.1.0
Summary: Client for the PunchRelay API: attendance from ZKTeco devices, devices, employees, locations, webhooks and webhook signature verification.
Author: PunchRelay
License-Expression: MIT
License-File: LICENSE
Keywords: adms,attendance,punchrelay,webhooks,zkteco
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx<1,>=0.27
Description-Content-Type: text/markdown

# PunchRelay Python SDK

A client for the PunchRelay API. Use it to read attendance from your ZKTeco devices, manage devices, employees, locations and webhooks, and verify webhook signatures.

- Python 3.11 or later
- Package: `punchrelay`, with a sync client (`PunchRelay`) and an asyncio client (`AsyncPunchRelay`), fully typed
- One dependency: [httpx](https://www.python-httpx.org/)
- API reference: `https://<api-host>/docs`

## Install

```sh
pip install punchrelay
```

## Quick start

Create a key on the dashboard's **API keys** page. Use a `read` key if you only read data, and a `read_write` key if you also make changes. The key tells the API which organisation you are, so no call takes a tenant id.

```python
import os
from datetime import datetime, timedelta, timezone

from punchrelay import PunchRelay

with PunchRelay(api_key=os.environ["PUNCHRELAY_API_KEY"], base_url="https://adms.example.com") as client:
    key = client.get_key_info()
    print(f"{key['tenantName']} ({key['scope']})")

    # Every punch in the last day, newest first. Pages are fetched as you iterate.
    since = datetime.now(timezone.utc) - timedelta(days=1)
    for punch in client.attendance.list_all(from_=since):
        print(punch["punchedAt"], punch["userId"], punch.get("userName"), "@", punch.get("deviceName"))
```

Create one client per key and reuse it. It caches the key's organisation after the first call, keeps a connection pool, and is safe to share between threads. Close it when you are done (`client.close()` or a `with` block).

### Async

`AsyncPunchRelay` has the same options and methods. Await the calls and iterate the `list_all` helpers with `async for`:

```python
from punchrelay import AsyncPunchRelay

async with AsyncPunchRelay(api_key=os.environ["PUNCHRELAY_API_KEY"], base_url="https://adms.example.com") as client:
    devices = await client.devices.list()
    async for punch in client.attendance.list_all(from_=since):
        ...
```

It runs on asyncio. Concurrent first calls share one key lookup.

## What's covered

| Area | Methods |
|---|---|
| `client.attendance` | `list`, `list_all`, `get`, `get_stats`, `export_csv`, `delete`, `delete_range` |
| `client.devices` | `list`, `list_models`, `create`, `update`, `delete`, `activate`, `deactivate`, `reboot`, `pull_attendance`, `pull_users`, `queue_command`, `list_commands`, `set_server_address` |
| `client.users` | `list`, `list_all`, `create`, `bulk_upsert`, `update`, `delete`, `sync`, `sync_one` |
| `client.locations` | `list`, `create`, `update`, `delete` |
| `client.webhooks` | `list`, `list_event_types`, `get`, `create`, `update`, `delete`, `rotate_secret`, `enable`, `disable`, `send_test`, `list_deliveries`, `list_all_deliveries`, `get_delivery`, `redeliver` |

### Requests and responses are dicts

Responses are plain dicts with the API's camelCase keys, exactly as the API sends them. Request bodies are dicts too. Their types are `TypedDict`s in `punchrelay.models` (`AttendanceItem`, `CreateDeviceRequest`, …), so mypy, Pyright and your editor check the keys:

```python
from punchrelay.models import UpsertUserRequest

user: UpsertUserRequest = {"pin": "1005", "name": "Ama Mensah"}
created = client.users.create(user)
print(created["id"])
```

Every key is typed as optional, because the API may add fields. Index the fields you rely on (`punch["userId"]`), or use `.get()` for the nullable ones.

Filters and paging are keyword arguments in snake_case: `from_` (with an underscore, because `from` is a Python keyword), `to`, `user_id`, `device_id`, `location_id`, `page`, `page_size`.

### Times and dates

- **Timestamps** (`from_` and `to` on attendance) accept a timezone-aware `datetime` or an ISO 8601 string. They are sent as UTC. A naive `datetime` raises `ValueError`, because the SDK cannot know which time zone you meant. Responses return timestamps as ISO 8601 strings.
- **Calendar dates** (`get_stats`, `pull_attendance`) are days in your organisation's time zone. Pass a `date` or `"YYYY-MM-DD"`.

### Anything not wrapped yet

`client.http` is the underlying [httpx](https://www.python-httpx.org/) client. It uses the same key, retries and errors as the methods above, with paths relative to `base_url`:

```python
tenant_id = client.get_tenant_id()
devices = client.http.get(f"/api/tenants/{tenant_id}/devices").json()
```

## Errors

Any non-2xx response raises `PunchRelayError`. It carries:

- `status`: the HTTP status
- `code`: the API's error code, such as `invalid_range` or `forbidden`
- `message`
- `body`: the raw response body
- `retry_after`: seconds, set on a 429

When the subscription is suspended (402), the error is a `SubscriptionSuspendedError`. It adds `invoice_number`, `pay_url`, `subscription_status` and `reason`.

```python
from punchrelay import PunchRelayError, SubscriptionSuspendedError

try:
    client.devices.reboot(device_id)
except SubscriptionSuspendedError as err:
    print(f"Suspended: pay {err.invoice_number} at {err.pay_url}")
except PunchRelayError as err:
    if err.status == 403:
        print("This key is read-only.")
    else:
        raise
```

Network failures raise httpx's `httpx.TransportError` subclasses. A call that runs out of time raises `httpx.TimeoutException`.

## Retries

These failures are retried up to `max_retries` times (default 3), with jittered exponential backoff:

- 429 Too Many Requests, on any method. The SDK waits for the server's `Retry-After`.
- 500, 502, 503 and 504, only on `GET`, `PUT`, `DELETE`, `HEAD` and `OPTIONS`.
- Network errors, on the same methods.

A `POST` is never retried after a 5xx or a network error, because it may already have run on the server.

If `Retry-After` is longer than `max_retry_delay` (default 30 s), the SDK raises the 429 immediately instead of waiting. Each key may make 120 requests per minute.

## Verifying webhooks

`verify_webhook(raw_body, headers, secret)` checks a webhook and returns its event. It does three things:

- checks the HMAC-SHA256 signature, using a constant-time comparison (`hmac.compare_digest`)
- rejects timestamps more than 5 minutes from your clock (change this with `tolerance=`, in seconds)
- parses the event

It raises `WebhookVerificationError` when any check fails.

**Pass the raw body, exactly as it was received.** If you parse the JSON and serialise it again, the bytes change and the signature no longer matches. `raw_body` can be `bytes` or `str`. `headers` can be your framework's request headers or a plain dict; names are matched case-insensitively.

### Flask

```python
import os

from flask import Flask, request
from punchrelay import WebhookVerificationError, is_attendance_created, verify_webhook

app = Flask(__name__)


@app.post("/webhooks/punchrelay")
def punchrelay_webhook():
    try:
        event = verify_webhook(request.get_data(), request.headers, os.environ["PUNCHRELAY_WEBHOOK_SECRET"])
    except WebhookVerificationError:
        return "", 401

    if is_attendance_created(event):
        # Queue it for processing. event["id"] stays the same across retries, so de-duplicate on it.
        print(event["data"]["userId"], event["data"]["punchedAt"])
    return "", 204
```

Read `request.get_data()` before touching `request.json` or `request.form`.

### FastAPI

Take the `Request` and read `await request.body()`. Don't declare a Pydantic model for the body, because FastAPI would parse it first.

```python
import os

from fastapi import FastAPI, Request, Response
from punchrelay import WebhookVerificationError, is_attendance_created, verify_webhook

app = FastAPI()


@app.post("/webhooks/punchrelay")
async def punchrelay_webhook(request: Request) -> Response:
    try:
        event = verify_webhook(await request.body(), request.headers, os.environ["PUNCHRELAY_WEBHOOK_SECRET"])
    except WebhookVerificationError:
        return Response(status_code=401)

    if is_attendance_created(event):
        ...
    return Response(status_code=204)
```

### Django

```python
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from punchrelay import WebhookVerificationError, is_attendance_created, verify_webhook


@csrf_exempt
@require_POST
def punchrelay_webhook(request):
    try:
        event = verify_webhook(request.body, request.headers, settings.PUNCHRELAY_WEBHOOK_SECRET)
    except WebhookVerificationError:
        return HttpResponse(status=401)

    if is_attendance_created(event):
        ...
    return HttpResponse(status=204)
```

Use `request.headers`, not `request.META`.

### Event types

| `event["type"]` | Guard | `event["data"]` |
|---|---|---|
| `attendance.created` | `is_attendance_created(event)` | `AttendanceCreated`: the punch, with `id`, `userId`, `userName`, `deviceId`, `deviceSerial`, `punchedAt`, `status`, `punch` |
| `webhook.test` | `is_webhook_test(event)` | `WebhookTest` |

The guards are `TypeGuard`s, so a type checker narrows `event["data"]` after them. New event types may be added. Ignore types you don't recognise and still answer 2xx.

`compute_signature(secret, timestamp, body)` produces a valid signature for your own tests.

## Options

| Option | Default | |
|---|---|---|
| `api_key` | (required) | `prk_live_…` |
| `base_url` | (required) | The API host |
| `tenant_id` | looked up | Set it to skip the one-time `GET /api/key-info` call |
| `max_retries` | 3 | 0 turns retries off |
| `retry_base_delay` | 0.5 | Seconds |
| `max_retry_delay` | 30 | Seconds |
| `timeout` | 100 | Seconds per call, including retries. `None` or 0 turns it off |
| `transport` | httpx's | An `httpx.BaseTransport` (`AsyncBaseTransport` for the async client), for a test stub or custom networking |
| `proxy` | none | A proxy URL for the default transport |

## Contributing

`src/punchrelay/_generated/models.py` is produced by [datamodel-code-generator](https://github.com/koxudaxi/datamodel-code-generator) from `sdks/openapi/v1.json`, with the options in `pyproject.toml`. Never edit it by hand. Set up once, then after the spec changes:

```sh
cd sdks/python
python -m venv .venv && .venv/bin/pip install -r requirements-dev.txt -e .   # Windows: .venv\Scripts\pip
cd .. && ./generate.sh python && cd python   # or generate.ps1 python
.venv/bin/ruff check . && .venv/bin/ruff format --check .
.venv/bin/mypy                               # strict; checks the hand-written layer against the new models
.venv/bin/pytest
```

`tests/test_coverage.py` fails when an operation in the spec has no method in the SDK, or when a method calls a path or HTTP method the spec doesn't have. Webhook signing is tested against `sdks/testdata/webhook-vectors.json`, which the .NET and Node SDKs also use and the API test suite checks against the server's signer.
