Metadata-Version: 2.5
Name: bulkit
Version: 0.1.1
Summary: Official Python SDK for bulkit.io — schedule and publish social media posts programmatically.
Project-URL: Homepage, https://bulkit.io
Project-URL: Documentation, https://docs.bulkit.io
Project-URL: Repository, https://github.com/bulkit-io/bulkit-python
Project-URL: Issues, https://github.com/bulkit-io/bulkit-python/issues
Author-email: Bulkit <support@bulkit.io>
License-Expression: MIT
License-File: LICENSE
Keywords: api,bulkit,publishing,scheduling,sdk,social-media
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1.0.0,>=0.27.0
Requires-Dist: pydantic<3.0.0,>=2.7.0
Requires-Dist: typing-extensions>=4.10.0
Provides-Extra: dev
Requires-Dist: mypy>=1.13.0; extra == 'dev'
Requires-Dist: pyright>=1.1.389; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest>=8.3.0; extra == 'dev'
Requires-Dist: respx>=0.21.1; extra == 'dev'
Requires-Dist: ruff>=0.8.0; extra == 'dev'
Description-Content-Type: text/markdown

# Bulkit Python SDK

Schedule and publish social posts from Python. The official [Bulkit](https://bulkit.io)
SDK provides typed sync and async clients for channels, posts, comments, media, analytics,
usage, and webhooks.

Requires **Python 3.10 or later**.

## Install

```sh
pip install bulkit
# or
uv add bulkit
```

Create an API key in **Developers → API & Webhooks** in the Bulkit app and set it in your
environment. Start with a test key; `bk_test_…` keys validate and save requests without
publishing to real accounts or billing.

```sh
export BULKIT_API_KEY=bk_test_your_key
```

## Quickstart

```python
from bulkit import Bulkit

with Bulkit() as client:  # reads BULKIT_API_KEY
    print(client.is_test_mode)
    channels = client.channels.list()
    post = client.posts.create(
        intent="draft",
        channels=[{"channel_id": channels[0].id, "blocks": [{"content": "Shipping today."}]}],
    )
    print(post.id, post.status)
```

The async client exposes the same methods and parameters:

```python
import asyncio
from bulkit import AsyncBulkit


async def main() -> None:
    async with AsyncBulkit() as client:
        channels = await client.channels.list()
        print(client.is_test_mode, channels)


asyncio.run(main())
```

Context managers close connections automatically. You can also call `client.close()` or
`await client.aclose()`. If you supply an `httpx.Client` or `httpx.AsyncClient` through
`http_client=`, you retain responsibility for closing it.

## Create and schedule posts

One post can target several channels, each with its own text, media, and platform options.
Additional blocks create a thread on platforms that support it.

```python
from bulkit import Bulkit, NOT_GIVEN

with Bulkit() as client:
    post = client.posts.create(
        intent="schedule",  # "draft", "schedule", or "now"
        scheduled_at="2027-01-15T09:00:00Z",
        tag_ids=NOT_GIVEN,
        channels=[
            {
                "channel_id": "chn_x",
                "blocks": [
                    {"content": "Our launch is here."},
                    {"content": "Here is how we built it."},
                ],
            },
            {
                "channel_id": "chn_linkedin",
                "blocks": [{"content": "A longer version for LinkedIn."}],
            },
        ],
        idempotency_key="campaign-launch-2027",
    )
```

Optional arguments default to `NOT_GIVEN` (also exported as `OMIT`), which omits the field
entirely from the JSON body. Arbitrary keys in `options`, `media_alt_text`, and
`media_user_tags` are preserved. Use `client.platforms.list()` and
`client.channels.capabilities(channel_id)` to inspect supported formats and limits.

Publishing is asynchronous: `intent="now"` and `posts.publish(id)` queue work and may return
`publishing`. Follow the result with webhooks or `posts.retrieve(id)`; individual channels
can fail independently.

## Media

```python
from pathlib import Path
from bulkit import Bulkit

with Bulkit() as client:
    image = client.media.upload(Path("photo.jpg"))
    # Also accepts a string path, binary stream, or (filename, content, MIME type) tuple.
    other = client.media.upload(b"image bytes", file_name="other.jpg")

    video = client.media.upload_multipart(
        Path("launch.mp4"),
        concurrency=4,
        idempotency_key="launch-video",
    )
    client.posts.create(
        intent="draft",
        channels=[
            {
                "channel_id": "chn_x",
                "blocks": [{"content": "Watch the launch.", "media_ids": [video.id]}],
            }
        ],
    )
```

`upload_multipart` streams file parts from disk, signs each batch, uploads it to storage,
and completes the session. It also accepts bytes or a seekable binary stream; stream
positions are restored afterward. Pass `file_name` for bytes or unnamed streams, and
`mime_type` if the filename does not identify a type. Concurrency is clamped to 1–100.
Multipart idempotency keys may contain at most 246 characters. Failed uploads abort their
session automatically. The same API is available with `await` on `AsyncBulkit`.

For explicit session management, use `media.uploads.start`, `sign_parts`, `complete`, and
`abort`.

## Pagination

Posts, comments, media, and webhook deliveries paginate automatically:

```python
with Bulkit() as client:
    for post in client.posts.list(status=["failed", "draft"]):
        print(post.id)

    # Or fetch one page at a time.
    page = client.posts.list(limit=50)
    print(page.data)
    while page.has_next_page():
        page = page.get_next_page()
        print(page.data)
```

```python
async with AsyncBulkit() as client:
    async for post in client.posts.list():  # no await before async for
        print(post.id)

    page = await client.posts.list(limit=50)
    async for batch in page.iter_pages():
        print(batch.data)
    # Manual paging: await page.get_next_page() when page.has_next_page().
```

## Response metadata

```python
with Bulkit() as client:
    response = client.with_raw_response.posts.list(limit=10)
    print(response.request_id, response.status_code)
    print(response.rate_limit.limit, response.rate_limit.remaining, response.rate_limit.reset)
    print(response.headers)
    page = response.parse()  # cached; response.data returns the same object
    print(page.data)
```

Every REST endpoint has a `with_raw_response` counterpart. Its `http_response` is the
underlying `httpx.Response`. Async raw methods are awaited; their `.parse()` is synchronous.
Include the request ID when contacting support.

## Errors, retries, and configuration

```python
from bulkit import APIError, Bulkit, QuotaExceededError

with Bulkit(max_retries=2, timeout=30.0) as client:
    try:
        post = client.posts.retrieve("post_123", max_retries=0)
    except QuotaExceededError:
        print("Plan allowance exhausted; inspect client.usage.retrieve().")
    except APIError as error:
        if error.code == "not_found":
            print("Post no longer exists")
        else:
            print(error.status_code, error.code, error.field, error.request_id)
```

| Status | Exception |
| --- | --- |
| 400 | `BadRequestError` |
| 401 | `AuthenticationError` |
| 402 | `QuotaExceededError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 409 | `ConflictError` |
| 413 | `PayloadTooLargeError` |
| 415 | `UnsupportedMediaTypeError` |
| 422 | `UnprocessableEntityError` |
| 429 | `RateLimitError` |
| 5xx | `InternalServerError` |

Network failures raise `APIConnectionError` or `APIConnectionTimeoutError`; invalid success
responses raise `APIResponseValidationError`. All SDK errors extend `BulkitError`.

The SDK retries connection failures, timeouts, 408, 429, 502, 503, 504, and
`409 request_in_progress` twice by default. It retries 500 on GET and DELETE only.
`QuotaExceededError` and other client errors are never retried. Backoff includes jitter;
numeric `Retry-After` values on 429 are honored up to 60 seconds.

POST and PUT automatically receive a UUID idempotency key, reused with identical body bytes
across retries. Supply `idempotency_key=` to reuse a logical write across process restarts
(255 characters maximum for individual REST calls). GET and DELETE never carry this header.

Configure `api_key`, `base_url` (or `BULKIT_BASE_URL`), `timeout` (60 seconds per I/O phase by
default), `max_retries`, `default_headers`, and `http_client` in either constructor.
Per-call options include `extra_headers`, `extra_query`, `timeout`, and `max_retries`.

## Webhooks

Verify the raw request body before using an event. Store your endpoint secret separately
from the API key. Both clients provide a synchronous `client.webhooks.unwrap` helper;
standalone `verify_webhook` needs no client.

FastAPI:

```python
import os
from fastapi import FastAPI, HTTPException, Request
from bulkit import WebhookVerificationError, verify_webhook

app = FastAPI()


@app.post("/webhooks/bulkit")
async def receive(request: Request):
    body = await request.body()
    try:
        event = verify_webhook(body, request.headers, secret=os.environ["BULKIT_WEBHOOK_SECRET"])
    except WebhookVerificationError as error:
        raise HTTPException(status_code=400, detail="Invalid webhook") from error
    # Deduplicate on event.id before processing; deliveries are at least once.
    return {"received": event.id}
```

Django:

```python
import os
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from bulkit import WebhookVerificationError, verify_webhook


@csrf_exempt
def receive(request):
    try:
        event = verify_webhook(
            request.body, request.headers, secret=os.environ["BULKIT_WEBHOOK_SECRET"]
        )
    except WebhookVerificationError:
        return HttpResponse(status=400)
    # Deduplicate and process event.id.
    return HttpResponse(status=200)
```

Use Django's `request.headers`, **not `request.META`**: verification expects HTTP header
names. Never deserialize and re-serialize the body before verifying. The default replay
tolerance is 300 seconds; `tolerance_seconds=None` disables the timestamp check.
Known events parse into typed payloads; new event types or forward-compatible payload changes fall back to `UnknownWebhookEvent` rather than failing verification.
Use `client.webhooks.test(endpoint_id)` to test your receiver and
`sign_webhook_payload(payload, secret)` to build signatures in local tests.

## Low-level requests

Access new routes while keeping authentication, retries, and error handling:

```python
with Bulkit() as client:
    data = client.get("/future-route", query={"limit": 10})
    created = client.post("/future-route", body={"name": "example"})
    updated = client.put("/future-route/id", body={"name": "updated"})
    client.delete("/future-route/id")
    data = client.request("GET", "/future-route")
```

Paths are relative to `/public/v1`; the default host is `https://api.bulkit.io`.

## Development

```sh
python -m pip install -e '.[dev]'
ruff check .
ruff format --check .
mypy --strict src tests
pyright
pytest --cov=bulkit
```

Read-only live smoke tests run only when `BULKIT_TEST_API_KEY` is set.

[Documentation](https://docs.bulkit.io) · [API keys](https://app.bulkit.io) ·
[MIT license](./LICENSE)
