---
title: "Python SDK"
description: "Publish, wait, paginate, and verify webhooks from Python."
---

> Documentation Index
> Fetch the complete documentation index at: https://pubnio.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

The `pubnio` package is the Python client for the PubNio HTTP API. It follows
the [TypeScript SDK](https://github.com/pubnio/mono/tree/dev/packages/sdk)
conventions for publishing, media, accounts, capabilities, and webhooks with
synchronous and asynchronous clients.

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

Python 3.11 or newer is required. The only runtime dependency is `httpx`.

## Publish in one call

```python
import os

from pubnio import PubNio

client = PubNio(api_key=os.environ["PUBNIO_API_KEY"])
workspace = client.workspace(workspace_id)

accepted = workspace.posts.create(
    text="CSV exports are live. Download a week of reports in one click.",
    platforms=["x"],
)
print(accepted["postId"], accepted["idempotencyKey"], accepted["targets"])
```

Send exactly one selector: `platforms`, `accounts`, or `targets`. The
server derives the provider and defaults the placement. Add `media` with
`{"url": ...}` or `{"mediaId": ...}` entries. Set `is_draft=True` to save
without submitting.

```python
accepted = workspace.posts.create(
    text="Launch day",
    media=[{"url": "https://cdn.example.com/launch.jpg"}],
    targets=[
        {
            "accountId": account_id,
            "provider": "instagram",
            "placement": "reel",
            "scheduledAt": "2026-12-02T15:00:00-08:00",
        }
    ],
)
```

## Wait for delivery

```python
result = workspace.posts.wait(accepted["postId"], timeout=60)
print(result["settled"], result["post"]["status"])

if not result["settled"]:
    print("Still working; retry after", result["retryAfterSeconds"])
```

`posts.wait` stops on a terminal delivery state or returns a still-pending
result at the deadline. `timeout=0` reads once. Media has the same bounded
pattern:

```python
intake = workspace.media.import_url("https://cdn.example.com/launch.mp4")
ready = workspace.media.wait(intake["mediaId"], timeout=30)
if ready["status"] == "ready":
    print(ready["asset"]["mediaId"])
```

## Async

```python
import os

from pubnio import AsyncPubNio

async with AsyncPubNio(api_key=os.environ["PUBNIO_API_KEY"]) as client:
    workspace = client.workspace(workspace_id)
    accepted = await workspace.posts.create(text="Launch day", platforms=["x"])
    result = await workspace.posts.wait(accepted["postId"], timeout=60)
```

Task cancellation stops a request or wait immediately and is re-raised as
`asyncio.CancelledError`.

## Pagination

```python
page = workspace.posts.list(is_draft=True, limit=50)
for post in page:
    print(post["postId"], post["textPreview"])

for post in workspace.posts.iterate_items(is_draft=True):
    print(post["postId"])
```

`iterate_pages` yields page envelopes and `iterate_items` yields rows. The
same pair exists on `media`, `webhooks`, and post attempt history. Filters
stay applied on every page. A repeated cursor raises
`PubNioPaginationError` instead of looping.

## Retries, timeouts, and idempotency

```python
client = PubNio(
    api_key=os.environ["PUBNIO_API_KEY"],
    base_url="https://pubnio.com",
    timeout=30.0,
    retries=2,
)
```

GET and HEAD requests retry twice with 250 ms and 500 ms backoff. Mutations
retry only when they carry an `Idempotency-Key`; unsafe writes are never
retried. `429` and `503` responses honor `Retry-After`. Every request sends
the API version the SDK was built against in `PubNio-Version`.

`posts.create`, `posts.publish`, `media.import_url`, and `media.upload`
generate an idempotency key when you omit one and return it as
`idempotencyKey`. A failed mutation keeps the resolved key on the error.

## Errors

```python
from pubnio import PubNioAPIError

try:
    workspace.posts.create(text="Launch day", platforms=["x"])
except PubNioAPIError as error:
    print(error.status, error.code, error.request_id)
    print(error.param, error.next_action, error.candidates)
```

`PubNioAPIError` exposes `status`, `code`, `title`, `detail`,
`request_id`, `param`, `next_action`, `candidates`, `retryable`,
`idempotency_key`, `supported_versions`, and `raw`. Network, timeout,
decode, pagination, and webhook failures use their own typed classes instead
of leaking `httpx` exceptions.

## Webhooks

```python
from pubnio import verify_webhook_signature

event = verify_webhook_signature(
    secret=os.environ["PUBNIO_WEBHOOK_SECRET"],
    body=raw_body,
    headers=request.headers,
)
print(event["id"], event["type"])
```

The helper implements Standard Webhooks HMAC-SHA256, a five-minute timestamp
tolerance, multiple `v1` signatures, and a constant-time comparison.
Failures raise `WebhookVerificationError` with a `reason` and `code`; the
message never includes the secret or body. Deduplicate deliveries by
`event["id"]`.

> **Next**
>
> Read [Publishing](https://pubnio.com/docs/publishing/) for targets and delivery outcomes,
> [Webhooks](https://pubnio.com/docs/webhooks/) for endpoint setup, or the [API
> reference](https://pubnio.com/api/v1/docs).

Source: https://pubnio.com/docs/sdk-python/index.mdx
