Send Webhooks with Flask

This guide will show you how to send webhooks with Flask 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 Flask + 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.

Flask 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 flask outpost_sdk python-dotenv

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.

Create a .env file in your Flask project root:

ADMIN_API_KEY=<YOUR_BEARER_TOKEN_HERE>
OUTPOST_URL=http://localhost:3333
FLASK_ENV=development

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 a Flask application that looks like the following:

First, create an Outpost service file (services/outpost_client.py):

import os
from dotenv import load_dotenv
from outpost_sdk import Outpost, models

load_dotenv()

class OutpostService:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(OutpostService, cls).__new__(cls)
            cls._instance._initialize()
        return cls._instance

    def _initialize(self):
        admin_api_key = os.getenv("ADMIN_API_KEY")
        server_url = os.getenv("OUTPOST_URL", "http://localhost:3333")

        if not admin_api_key:
            raise ValueError("Please set the ADMIN_API_KEY environment variable.")

        self.client = Outpost(
            security=models.Security(admin_api_key=admin_api_key),
            server_url=f"{server_url}/api/v1",
        )

    def get_client(self):
        return self.client

Then, create a Flask blueprint (webhooks/routes.py):

import os
import uuid
from flask import Blueprint, request, jsonify
from outpost_sdk import models
from services.outpost_client import OutpostService

webhooks_bp = Blueprint("webhooks", __name__, url_prefix="/webhooks")

outpost_service = OutpostService()
outpost = outpost_service.get_client()


@webhooks_bp.route("/setup", methods=["POST"])
def webhook_setup():
    """
    Create a new tenant and destination for webhook delivery.
    """
    try:
        tenant_id = f"tenant_{str(uuid.uuid4())}"
        topic = "user.created"
        destination_name = f"My Test Destination {str(uuid.uuid4())}"

        # 1. Create a tenant
        print(f"Creating tenant: {tenant_id}")
        tenant = outpost.tenants.upsert(tenant_id=tenant_id)
        print("Tenant created successfully:", tenant)

        # 2. Create a destination for the tenant
        print(f"Creating destination: {destination_name} for tenant {tenant_id}...")
        destination = outpost.destinations.create(
            tenant_id=tenant_id,
            destination_create=models.DestinationCreateWebhook(
                type=models.DestinationCreateWebhookType.WEBHOOK,
                config=models.WebhookConfig(
                    url="https://example.com/webhook-receiver"
                ),
                topics=[topic],
            ),
        )
        print("Destination created successfully:", destination)

        return jsonify({
            "success": True,
            "message": "Tenant and destination created successfully",
            "data": {
                "tenant_id": tenant.id if hasattr(tenant, 'id') else tenant_id,
                "destination_id": destination.id if hasattr(destination, 'id') else None,
            },
        }), 200

    except Exception as e:
        print(f"An error occurred: {e}")
        return jsonify({
            "success": False,
            "error": str(e),
        }), 500


@webhooks_bp.route("/publish", methods=["POST"])
def publish_event():
    """
    Publish an event to a tenant's topic.
    """
    try:
        data = request.get_json()

        if not data:
            return jsonify({
                "success": False,
                "error": "Request body must be JSON",
            }), 400

        tenant_id = data.get("tenant_id")
        topic = data.get("topic")

        if not tenant_id or not topic:
            return jsonify({
                "success": False,
                "error": "tenant_id and topic are required",
            }), 400

        event_payload = {
            "user_id": "user_456",
            "order_id": "order_xyz",
            "timestamp": str(uuid.uuid4()),
        }

        print(f"Publishing event to topic {topic} for tenant {tenant_id}...")
        event = outpost.publish.event(
            data=event_payload,
            tenant_id=tenant_id,
            topic=topic,
            eligible_for_retry=True,
        )

        print("Event published successfully")
        return jsonify({
            "success": True,
            "message": "Event published successfully",
            "event_id": event.id if hasattr(event, 'id') else None,
        }), 200

    except Exception as e:
        print(f"An error occurred: {e}")
        return jsonify({
            "success": False,
            "error": str(e),
        }), 500


@webhooks_bp.route("/receiver", methods=["POST"])
def webhook_receiver():
    """
    Receive and process incoming webhooks from Outpost.
    """
    try:
        data = request.get_json()
        print("Webhook received:", data)

        return jsonify({
            "success": True,
            "message": "Webhook received",
        }), 200

    except Exception as e:
        print(f"An error occurred: {e}")
        return jsonify({
            "success": False,
            "error": str(e),
        }), 500


@webhooks_bp.route("/portal/<tenant_id>", methods=["GET"])
def get_portal_url(tenant_id):
    """
    Get the Tenant User Portal URL for a specific tenant.
    """
    try:
        portal_url = outpost.tenants.get_portal_url(tenant_id=tenant_id)

        return jsonify({
            "success": True,
            "portal_url": portal_url.url if hasattr(portal_url, 'url') else None,
        }), 200

    except Exception as e:
        print(f"An error occurred: {e}")
        return jsonify({
            "success": False,
            "error": str(e),
        }), 500

Finally, create your main Flask application (app.py):

import os
from dotenv import load_dotenv
from flask import Flask
from webhooks.routes import webhooks_bp

load_dotenv()

app = Flask(__name__)

# Configuration
app.config['JSON_SORT_KEYS'] = False

# Register blueprints
app.register_blueprint(webhooks_bp)


@app.route("/health", methods=["GET"])
def health_check():
    """
    Health check endpoint.
    """
    return {
        "status": "ok"
    }, 200


if __name__ == "__main__":
    debug = os.getenv("FLASK_ENV") == "development"
    app.run(debug=debug, host="0.0.0.0", port=5000)

Then create a requirements.txt file:

flask==3.0.0
outpost-sdk==1.0.0
python-dotenv==1.0.0

Install dependencies and run:

pip install -r requirements.txt
python app.py

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. Then redirect your users to this URL or use it in an iframe in your Flask templates.

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 using Flask. 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.