Skip to main content

Overview

The Brew SDK provides methods to trigger automations and retrieve automation configuration. Automations are triggered via API with a typed payload that matches the automation’s configured schema.
New to automation triggers? Start with the Events & Automation Triggers guide to understand how triggers work, then return here for SDK-specific implementation details.

Trigger an Automation

Trigger an automation by ID with a payload:
from brew_sdk import BrewSDK

client = BrewSDK()

# Note: payload keys use camelCase to match the API
result = client.automations.trigger(
    "auto_abc123",
    payload={
        "email": "[email protected]",
        "firstName": "John",
        "orderId": "ORD-12345",
        "orderTotal": 99.99,
    }
)

print(f"Execution ID: {result.execution_id}")
print(f"Status: {result.status}")  # "running"
print(f"Contact: {result.contact.action}")  # "created" or "updated"

Parameters

ParameterTypeRequiredDescription
automation_idstrYesThe automation ID from Brew
payloaddictYesData matching the automation’s payload schema
metadatadictNoOptional metadata to attach to the execution

Response

@dataclass
class TriggerResponse:
    success: bool
    execution_id: str    # Unique execution ID for tracking
    automation_id: str   # The triggered automation
    event_id: str        # The event ID configured for this automation
    status: str          # "running"
    contact: ContactResult  # Contains email and action ("created" or "updated")

@dataclass
class ContactResult:
    email: str           # Contact email address
    action: str          # "created" or "updated"
The contact field shows the result of the automatic contact upsert. When you trigger an automation, Brew automatically creates or updates the contact based on the email in your payload.

Get Automation Info

Retrieve an automation’s trigger configuration and payload schema:
info = client.automations.get_trigger_info("auto_abc123")

print(f"Automation: {info.name}")
print(f"Event ID: {info.event_definition.event_id}")
print(f"Schema: {info.event_definition.payload_schema}")

Real-World Examples

For detailed guides on common automation scenarios (welcome emails, order confirmations, payment recovery, trial reminders), see Events & Automation Triggers.

E-commerce Order Confirmation

from brew_sdk import BrewSDK
from brew_sdk.errors import BadRequestError

client = BrewSDK()

def send_order_confirmation(order):
    try:
        # Keep payload flat - avoid nested objects
        # Note: payload keys use camelCase to match the API
        result = client.automations.trigger(
            "auto_order_confirm",
            payload={
                "email": order.customer_email,
                "firstName": order.customer_name.split()[0],
                "orderId": order.id,
                "orderTotal": float(order.total),
                "itemCount": len(order.items),
                "shippingCity": order.shipping_address.city,
                "shippingState": order.shipping_address.state,
            }
        )

        print(f"Order confirmation triggered: {result.execution_id}")
        print(f"Contact {result.contact.action}: {result.contact.email}")
        return result

    except BadRequestError as e:
        print(f"Invalid payload: {e.message}")
        raise

User Onboarding Flow

def trigger_welcome_flow(user):
    # Payload keys use camelCase to match the API
    client.automations.trigger(
        "auto_welcome_sequence",
        payload={
            "email": user.email,
            "firstName": user.first_name,
            "plan": user.plan,
            "signupSource": user.referrer or "direct",
            "trialEndsAt": user.trial_end_date.isoformat() if user.trial_end_date else None,
        }
    )

Payment Failed Notification

def notify_payment_failed(subscription):
    # Payload keys use camelCase to match the API
    client.automations.trigger(
        "auto_payment_failed",
        payload={
            "email": subscription.customer_email,
            "firstName": subscription.customer_name,
            "amount": float(subscription.amount),
            "failureReason": subscription.last_failure_reason,
            "retryUrl": f"https://app.example.com/billing/retry/{subscription.id}",
            "attemptNumber": subscription.failed_attempts,
        }
    )

Error Handling

The SDK raises typed exceptions for different failure scenarios:
from brew_sdk import BrewSDK
from brew_sdk.errors import (
    BadRequestError,
    NotFoundError,
    AuthenticationError,
    RateLimitError,
)

client = BrewSDK()

try:
    client.automations.trigger(
        "auto_abc123",
        payload={
            "email": "[email protected]",
            # Missing required fields...
        }
    )
except BadRequestError as e:
    # Payload validation failed
    print(f"Invalid payload: {e.message}")
    # e.details may contain field-specific errors
except NotFoundError:
    # Automation doesn't exist
    print("Automation not found")
except AuthenticationError:
    # Invalid API key
    print("Check your API key")
except RateLimitError as e:
    # Too many requests
    print(f"Rate limited, retry after: {e.retry_after}")

Django Integration

# views.py
from django.http import JsonResponse
from brew_sdk import BrewSDK

client = BrewSDK()

def handle_order_complete(request, order_id):
    order = Order.objects.get(id=order_id)

    # Trigger order confirmation automation
    # Note: payload keys use camelCase to match the API
    result = client.automations.trigger(
        "auto_order_confirm",
        payload={
            "email": order.customer.email,
            "firstName": order.customer.first_name,
            "orderId": str(order.id),
            "orderTotal": float(order.total),
        }
    )

    return JsonResponse({
        "success": True,
        "execution_id": result.execution_id,
        "contact_action": result.contact.action,
    })

FastAPI Integration

from fastapi import FastAPI, HTTPException
from brew_sdk import BrewSDK
from brew_sdk.errors import BadRequestError

app = FastAPI()
client = BrewSDK()

@app.post("/orders/{order_id}/confirm")
async def confirm_order(order_id: str):
    order = await get_order(order_id)

    try:
        # Payload keys use camelCase to match the API
        result = client.automations.trigger(
            "auto_order_confirm",
            payload={
                "email": order.customer_email,
                "firstName": order.customer_name,
                "orderId": order.id,
                "orderTotal": order.total,
            }
        )
        return {
            "execution_id": result.execution_id,
            "contact_action": result.contact.action,
        }

    except BadRequestError as e:
        raise HTTPException(status_code=400, detail=str(e))

Best Practices

For important automations (order confirmations, payment notifications), use idempotency to prevent duplicates:
client.automations.trigger(
    "auto_order_confirm",
    payload=payload,
    idempotency_key=f"order-{order.id}",
)
Get the automation’s schema and validate locally before triggering:
info = client.automations.get_trigger_info("auto_abc123")
schema = info.event_definition.payload_schema

# Validate required fields
required = schema.get("required", [])
for field in required:
    if field not in payload:
        raise ValueError(f"Missing required field: {field}")
Always wrap trigger calls in try-except and handle specific error types:
from tenacity import retry, stop_after_attempt, wait_exponential

@retry(stop=stop_after_attempt(3), wait=wait_exponential())
def trigger_with_retry(automation_id, payload):
    try:
        return client.automations.trigger(automation_id, payload=payload)
    except BadRequestError:
        # Don't retry validation errors
        raise
    except RateLimitError as e:
        # Let tenacity handle the retry
        raise

Next Steps

Need Help?

Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you:

Search Documentation

Type in the “Ask any question” search bar at the top left to instantly find relevant documentation pages.

ChatGPT/Claude Integration

Click “Open in ChatGPT” at the top right of any page to analyze documentation with ChatGPT or Claude for deeper insights.