Skip to main content

Official Python SDK for Webhook Platform

Project description

webhook-platform

Official Python SDK for Webhook Platform.

Installation

pip install webhook-platform

Quick Start

from webhook_platform import WebhookPlatform, Event

client = WebhookPlatform(
    api_key="wh_live_your_api_key",
    base_url="http://localhost:8080",  # optional
)

# Send an event
event = client.events.send(
    Event(
        type="order.completed",
        data={
            "order_id": "ord_12345",
            "amount": 99.99,
            "currency": "USD",
        },
    )
)

print(f"Event created: {event.event_id}")
print(f"Deliveries created: {event.deliveries_created}")

API Reference

Events

from webhook_platform import Event

# Send event with idempotency key
event = client.events.send(
    Event(type="order.completed", data={"order_id": "123"}),
    idempotency_key="unique-key",
)

Endpoints

from webhook_platform import EndpointCreateParams, EndpointUpdateParams

# Create endpoint
endpoint = client.endpoints.create(
    project_id,
    EndpointCreateParams(
        url="https://api.example.com/webhooks",
        description="Production webhooks",
        enabled=True,
    ),
)

# List endpoints
endpoints = client.endpoints.list(project_id)

# Update endpoint
client.endpoints.update(
    project_id,
    endpoint_id,
    EndpointUpdateParams(enabled=False),
)

# Delete endpoint
client.endpoints.delete(project_id, endpoint_id)

# Rotate secret
updated = client.endpoints.rotate_secret(project_id, endpoint_id)
print(f"New secret: {updated.secret}")

# Test endpoint connectivity
result = client.endpoints.test(project_id, endpoint_id)
print(f"Test {'passed' if result.success else 'failed'}: {result.latency_ms}ms")

Subscriptions

from webhook_platform import SubscriptionCreateParams

# Subscribe endpoint to event types
subscription = client.subscriptions.create(
    project_id,
    SubscriptionCreateParams(
        endpoint_id=endpoint.id,
        event_types=["order.completed", "order.cancelled"],
        enabled=True,
    ),
)

# List subscriptions
subscriptions = client.subscriptions.list(project_id)

# Update subscription
client.subscriptions.update(
    project_id,
    subscription_id,
    event_types=["order.*"],
)

# Delete subscription
client.subscriptions.delete(project_id, subscription_id)

Deliveries

from webhook_platform import DeliveryListParams, DeliveryStatus

# List deliveries with filters
deliveries = client.deliveries.list(
    project_id,
    DeliveryListParams(status=DeliveryStatus.FAILED, page=0, size=20),
)

print(f"Total failed: {deliveries.total_elements}")

# Get delivery attempts
attempts = client.deliveries.get_attempts(delivery_id)
for attempt in attempts:
    print(f"Attempt {attempt.attempt_number}: {attempt.http_status} ({attempt.latency_ms}ms)")

# Replay failed delivery
client.deliveries.replay(delivery_id)

Webhook Signature Verification

Verify incoming webhooks in your endpoint:

from webhook_platform import verify_signature, construct_event, WebhookPlatformError

# Flask example
from flask import Flask, request

app = Flask(__name__)

@app.route("/webhooks", methods=["POST"])
def handle_webhook():
    payload = request.get_data(as_text=True)
    headers = dict(request.headers)
    secret = os.environ["WEBHOOK_SECRET"]

    try:
        # Option 1: Just verify
        verify_signature(payload, headers.get("X-Signature", ""), secret)

        # Option 2: Verify and parse
        event = construct_event(payload, headers, secret)

        print(f"Received {event.type}: {event.data}")

        # Handle the event
        if event.type == "order.completed":
            handle_order_completed(event.data)

        return "OK", 200

    except WebhookPlatformError as e:
        print(f"Webhook verification failed: {e.message}")
        return "Invalid signature", 400

FastAPI Example

from fastapi import FastAPI, Request, HTTPException
from webhook_platform import construct_event, WebhookPlatformError

app = FastAPI()

@app.post("/webhooks")
async def handle_webhook(request: Request):
    payload = await request.body()
    headers = dict(request.headers)

    try:
        event = construct_event(
            payload.decode("utf-8"),
            headers,
            os.environ["WEBHOOK_SECRET"],
        )

        # Process event...
        return {"status": "ok"}

    except WebhookPlatformError as e:
        raise HTTPException(status_code=400, detail=e.message)

Error Handling

from webhook_platform import (
    WebhookPlatformError,
    RateLimitError,
    AuthenticationError,
    ValidationError,
)

try:
    client.events.send(Event(type="test", data={}))
except RateLimitError as e:
    # Wait and retry
    print(f"Rate limited. Retry after {e.retry_after_ms}ms")
    time.sleep(e.retry_after_ms / 1000)
except AuthenticationError:
    print("Invalid API key")
except ValidationError as e:
    print(f"Validation failed: {e.field_errors}")
except WebhookPlatformError as e:
    print(f"Error {e.status}: {e.message}")

Configuration

client = WebhookPlatform(
    api_key="wh_live_xxx",          # Required: Your API key
    base_url="https://api.example.com",  # Optional: API base URL
    timeout=30,                     # Optional: Request timeout in seconds (default: 30)
)

Type Hints

This SDK includes full type hints for better IDE support:

from webhook_platform import (
    Event,
    EventResponse,
    Endpoint,
    Delivery,
    DeliveryStatus,
)

Development

Running Tests

Local (requires Python 3.8+):

pip install -e ".[dev]"
pytest

Docker:

docker run --rm -v $(pwd):/app -w /app python:3.11-slim sh -c "pip install -e '.[dev]' && pytest"

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

webhook_platform-1.0.1.tar.gz (14.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

webhook_platform-1.0.1-py3-none-any.whl (14.3 kB view details)

Uploaded Python 3

File details

Details for the file webhook_platform-1.0.1.tar.gz.

File metadata

  • Download URL: webhook_platform-1.0.1.tar.gz
  • Upload date:
  • Size: 14.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for webhook_platform-1.0.1.tar.gz
Algorithm Hash digest
SHA256 1cd5809b124fcc410b8f68d673976fd46e301976c4a0c5dd066655eb055be008
MD5 6e74819577dcd10fa857e040cc564d67
BLAKE2b-256 6048d39142f662c341ddeccb7a3ef66408e8e9a0dc8f158c2044903b4576f076

See more details on using hashes here.

File details

Details for the file webhook_platform-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for webhook_platform-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 2c7e449b57cd8b3327e7e3c61d714b8f1021729dba8e8928a0220f2713ac00f1
MD5 a674bb9d766761e073f630d4ad0c03ad
BLAKE2b-256 bf9797bc65c38b1c90e2e56109a0a54ff1b7ba93ad69c5bba1572f9e1b708045

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page