Send Webhooks with Python
This guide will show you how to send webhooks with Python using Hookdeck's Outpost — an open-source event dispatcher. Outpost gives you a world-class webhook and event destination infrastructure in minutes for 1/10th the cost of alternatives.
Outpost supports Event Destinations, allowing you to deliver events to webhook endpoints, as well as to queues, and popular brokers or event gateways. These include AWS SQS, RabbitMQ, GCP Pub/Sub, Amazon EventBridge, Kafka, and more—all from a single platform.
The team behind it has drawn on their experience running Hookdeck Event Gateway and delivering over 100 billion events to thousands of customers.
Why use Outpost?
Sending webhooks can be trickier than you think. From managing fan‑out load, retries and backoff, to endpoint health management, and security/operational overhead. Outpost takes care of all of that so you only need to think about is how to send a webhook.
How to Send Webhooks with Python + Outpost
Start by deploying an Outpost instance locally, via Docker, or deploy to production. For guidance, check out the Outpost quickstart or the GitHub repository.
Python Support in Outpost
You can interact with Outpost using the Python SDK or the REST API. Each SDK provides a convenient way to interact with the Outpost API, including publishing events, managing topics, and configuring destinations.
pip install outpost_sdk
Set Your Admin API Key
Before you can start making calls to the Outpost API you need to set an API key. The API uses bearer token authentication with a token of your choice configured through the API_KEY environment variable.
Send Webhooks (Publish Events)
In order to send a webhook, you have to instantiate Outpost, create a tenant, and create a destination for that tenant. Then you’re ready to publish events to it.
Create an Outpost instance
with Outpost() as outpost
You can set the security parameters through the security optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:
with Outpost(
security=models.Security(
admin_api_key="<YOUR_BEARER_TOKEN_HERE>",
),
) as outpost
Create a new tenant.
A tenant in Outpost represents a user/team/organization in your product. Use the upsert() method to idempotently create or update a tenant: outpost.tenants.upsert()
Create a destination for that tenant.
The create() method is used to specify a new destination for the tenant. A destination is a specific instance of a destination type. For example, a webhook destination with a particular URL.
The request body structure depends on the destination type. Here we’re creating a destination for a webhook, but it could be SQS, RabbitMQ, etc.
res = outpost.destinations.create(destination_create={
"tenant_id": tenant_id,
"id": user-provided-id,
"type": models.DestinationWebhook,
"topics": models.TopicsEnum.WILDCARD_,
"config": {
"url": "https://example.com/webhook-receiver",
},
})
Note that we specify topics. A topic is a way to categorize events and is a common concept found in Pub/Sub messaging.
Publish an event for the created tenant.
You can now use the publish() method to send an event to the specified topic, routed to a specific destination.
res = outpost.publish.event(data={
"user_id": "userid",
"status": "active",
}, id="evt_custom_123", tenant_id="<TENANT_ID>", destination_id="<DESTINATION_ID>", topic="topic.name", metadata={
"source": "crm",
})
id: Is optional but recommended. If left empty, it will be generated by hashing the topic, data, and timestamp.
tenant_id: The tenant ID to publish the event must match an existing tenant, otherwise it will be ignored.
destination_id: Optional. Used to force delivery to a specific destination regardless of the topic.
topic: Optional. Assumed to match ANY topic if left empty. If set, it must match one of the configured topics.
metadata: Arbitrary key-value mapping for event metadata.
data: The data JSON object will be sent as the webhook body. Now, every time you publish an event to this tenant, Outpost will send an HTTP POST request with the data payload to the destination URL.
Other fields:
eligible_for_retry: Optional, defaults to true. Controls whether an event should be automatically retried.
retries: Configuration to override the default retry behavior of the client.
Complete Example
Combining the examples above, you should end up with something that looks like the following:
app.py
import typer
from example.create_destination import run as create_destination
from example.publish_event import run as publish_event
from example.auth import run as auth
app = typer.Typer()
app.command("auth")(auth)
app.command("create-destination")(create_destination)
app.command("publish-event")(publish_event)
if __name__ == "__main__":
app()
example/auth.py
import os
import sys
from dotenv import load_dotenv
from outpost_sdk import Outpost, models
def with_jwt(outpost: Outpost, jwt: str):
print("--- Running with Tenant JWT ---")
try:
destinations_res = outpost.destinations.list()
print("Destinations listed successfully using JWT:")
print(destinations_res)
except Exception as e:
print(f"Error listing destinations with JWT: {e}")
def with_admin_api_key(outpost: Outpost, tenant_id: str):
print("--- Running with Admin API Key ---")
try:
health_res = outpost.health.check()
print("Health check result:")
print(health_res)
destinations_res = outpost.destinations.list(tenant_id=tenant_id)
print(
f"Destinations listed successfully using Admin Key for tenant {tenant_id}:" # noqa E501
)
print(destinations_res)
token_res = outpost.tenants.get_token(tenant_id=tenant_id)
print(f"Tenant token obtained for tenant {tenant_id}:")
print(token_res)
if token_res and hasattr(token_res, "token") and token_res.token:
# Re-initialize outpost with JWT for this part of the test
security_config = models.Security(tenant_jwt=token_res.token)
with Outpost(
security=security_config,
server_url=outpost.sdk_configuration.server_url,
) as jwt_outpost:
with_jwt(jwt_outpost, token_res.token)
else:
print("Could not obtain tenant token.")
except Exception as e:
print(f"Error during admin operations: {e}")
def run():
load_dotenv()
admin_api_key = os.getenv("ADMIN_API_KEY")
tenant_id = os.getenv("TENANT_ID")
server_url = os.getenv("SERVER_URL")
if not admin_api_key:
print("Error: ADMIN_API_KEY not set.")
sys.exit(1)
if not tenant_id:
print("Error: TENANT_ID not set.")
sys.exit(1)
if not server_url:
print("Error: SERVER_URL not set.")
sys.exit(1)
api_server_url = f"{server_url}/api/v1"
security_config = models.Security(admin_api_key=admin_api_key)
with Outpost(security=security_config, server_url=api_server_url) as outpost:
with_admin_api_key(outpost, tenant_id)
print("--- Example finished ---")
example/create_destination.py
import os
import sys
import questionary
from dotenv import load_dotenv
from outpost_sdk import Outpost, models
def run():
"""
Interactively creates a new destination for a tenant.
"""
load_dotenv()
admin_api_key = os.getenv("ADMIN_API_KEY")
tenant_id = os.getenv("TENANT_ID", "hookdeck")
server_url = os.getenv("OUTPOST_URL", "http://localhost:3333")
if not admin_api_key:
print("Please set the ADMIN_API_KEY environment variable.")
sys.exit(1)
sdk = Outpost(
security=models.Security(admin_api_key=admin_api_key),
server_url=f"{server_url}/api/v1",
)
sdk.tenants.upsert(tenant_id=tenant_id)
connection_string = questionary.text(
"Enter Azure Service Bus Connection String:"
).ask()
if connection_string is None:
sys.exit(0)
topic_or_queue_name = questionary.text(
"Enter Azure Service Bus Topic or Queue name:"
).ask()
if topic_or_queue_name is None:
sys.exit(0)
try:
resp = sdk.destinations.create(
tenant_id=tenant_id,
destination_create=models.DestinationCreateAzureServiceBus(
type=(models.DestinationCreateAzureServiceBusType.AZURE_SERVICEBUS),
credentials=models.AzureServiceBusCredentials(
connection_string=connection_string
),
config=models.AzureServiceBusConfig(name=topic_or_queue_name),
topics="*",
),
)
if resp:
print("Destination created successfully:", resp)
else:
print("Failed to create destination, response was empty.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
run()
example/publish_event.py
import os
from dotenv import load_dotenv
from outpost_sdk import Outpost, models
def run():
load_dotenv()
server_url = os.environ.get("SERVER_URL", "http://localhost:3333")
admin_api_key = os.environ.get("ADMIN_API_KEY")
tenant_id = os.environ.get("TENANT_ID", "hookdeck")
if not admin_api_key:
raise Exception("ADMIN_API_KEY not set")
client = Outpost(
server_url=f"{server_url}/api/v1",
security=models.Security(
admin_api_key=admin_api_key,
),
)
topic = "order.created"
payload = {
"order_id": "ord_2Ua9d1o2b3c4d5e6f7g8h9i0j",
"customer_id": "cus_1a2b3c4d5e6f7g8h9i0j",
"total_amount": "99.99",
"currency": "USD",
"items": [
{
"product_id": "prod_1a2b3c4d5e6f7g8h9i0j",
"name": "Example Product 1",
"quantity": 1,
"price": "49.99",
},
{
"product_id": "prod_9z8y7x6w5v4u3t2s1r0q",
"name": "Example Product 2",
"quantity": 1,
"price": "50.00",
},
],
}
res = client.publish.event(
topic=topic,
data=payload,
tenant_id=tenant_id,
)
if res is not None:
print("Event published successfully")
print(f"Event ID: {res.id}")
else:
print("Failed to publish event")
Expose Tenant User Portal
Your application can offer the user the option to configure their destination, view and retry their events using a themeable Tenant User Portal. Note that if the portal is used, then the Outpost API needs to be exposed to the public internet (or proxy requests to the Outpost API).
You can use get_portal_url() to return a redirect URL containing a JWT to authenticate the user with the portal, like so: outpost.tenants.get_portal_url(). Then redirect your users to this URL or use it in an iframe.
Build your own UI
While Outpost offers a user portal, you may want to build your own UI for users to manage their destinations and view their events. The portal is built using the Outpost API with JWT authentication. You can leverage the same API to build your own UI.
Help with debugging and testing webhooks
To help you and your users work with webhooks, we provide some additional tools. Like Hookdeck Console, a web-based inspector to test and debug incoming webhooks. As well as the Hookdeck CLI to forward webhook events to a local web server.
More information
That's everything you need to start sending webhooks with Outpost. For more information, please check out the Outpost documentation.
If you have any questions, we’d love to help. Please join the Hookdeck community on Slack.