Skip to main content

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
  • API reference: https://<api-host>/docs

Install

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.

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:

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 TypedDicts in punchrelay.models (AttendanceItem, CreateDeviceRequest, …), so mypy, Pyright and your editor check the keys:

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 client. It uses the same key, retries and errors as the methods above, with paths relative to base_url:

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.

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

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.

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

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 TypeGuards, 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 from sdks/openapi/v1.json, with the options in pyproject.toml. Never edit it by hand. Set up once, then after the spec changes:

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.

Metadata

Release files for punchrelay 0.1.0

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

Source distribution (sdist)

Source distribution for punchrelay 0.1.0
File Size Uploaded Provenance Actions
punchrelay-0.1.0.tar.gz 23.1 kB With provenance Details for punchrelay-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for punchrelay 0.1.0
File Interpreter ABI Platform Actions
punchrelay-0.1.0-py3-none-any.whl Python 3 none any Details for punchrelay-0.1.0-py3-none-any.whl

Total release size: 53.4 kB

Release files / punchrelay-0.1.0.tar.gz

Download URL punchrelay-0.1.0.tar.gz
Size 23.1 kB
Tags Source
SHA-256 checksum
How to use checksums
6adc961d7c7e4ad23168d2d9b980cba1d17f7e48b159dfd7d652cd35aa46b046
BLAKE2b-256 checksum
How to use checksums
4923866f6a154b376aa98a426b1352ed78c2d61e0cad6bbc570f9a36a72d0986
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / punchrelay-0.1.0-py3-none-any.whl

Download URL punchrelay-0.1.0-py3-none-any.whl
Size 30.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1c30b7537d5702f50f095fbf948741f7a72018e678a559f587b656b3caa50105
BLAKE2b-256 checksum
How to use checksums
890ee3456b62c1f0ff92d693f90cb6a93c4f4220ba2e0302a28e75e075c23301
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for punchrelay 0.1.0

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for punchrelay-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

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