> ## Documentation Index
> Fetch the complete documentation index at: https://demeterrr.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Execute Sequence

> Trigger a sequence for one or more contacts (KEY ENDPOINT)

<Note>
  **Most Important Endpoint**: This is the primary integration point for triggering automated customer workflows.
</Note>

## Authentication

Requires `sequences:execute` scope.

## Path Parameters

<ParamField path="id" type="string" required>
  Sequence UUID
</ParamField>

## Request Body

<ParamField body="contacts" type="array" required>
  Array of contact objects (min: 1, max: 100)

  <Expandable title="Contact Object">
    <ParamField body="email" type="string" required>
      Contact email address
    </ParamField>

    <ParamField body="firstName" type="string">
      Contact first name
    </ParamField>

    <ParamField body="lastName" type="string">
      Contact last name
    </ParamField>

    <ParamField body="phone" type="string">
      Contact phone number (required if sequence includes SMS steps)
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="locationId" type="string">
  Location UUID to associate with all contacts
</ParamField>

<ParamField body="employeeId" type="string">
  Employee UUID to associate with all contacts (for attribution)
</ParamField>

## How It Works

1. **Contact Creation/Update**: Contacts are created if they don't exist, or updated if they do (matched by email)
2. **Sequence Validation**: Sequence must be `active` status
3. **Sending Creation**: Creates a `sending` record for each contact
4. **Background Execution**: Triggers Inngest background job to execute the sequence steps
5. **Immediate Response**: Returns immediately without waiting for execution to complete

<Tip>
  Use this endpoint to trigger surveys after purchase, onboarding sequences for new customers, or review requests after service completion.
</Tip>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://app.demeterrr.com/api/v1/sequences/880e8400-e29b-41d4-a716-446655440000/execute \
    -H "X-API-Key: dem_your_key_here" \
    -H "Content-Type: application/json" \
    -d '{
      "contacts": [
        {
          "email": "customer1@example.com",
          "firstName": "Alice",
          "lastName": "Johnson",
          "phone": "+15551234567"
        },
        {
          "email": "customer2@example.com",
          "firstName": "Bob",
          "lastName": "Williams",
          "phone": "+15559876543"
        }
      ],
      "locationId": "660e8400-e29b-41d4-a716-446655440000",
      "employeeId": "770e8400-e29b-41d4-a716-446655440000"
    }'
  ```

  ```javascript JavaScript - Trigger After Purchase theme={null}
  // When customer completes purchase
  async function triggerPostPurchaseSurvey(order) {
    const response = await fetch(
      'https://app.demeterrr.com/api/v1/sequences/880e8400-e29b-41d4-a716-446655440000/execute',
      {
        method: 'POST',
        headers: {
          'X-API-Key': 'dem_your_key_here',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          contacts: [{
            email: order.customerEmail,
            firstName: order.customerFirstName,
            lastName: order.customerLastName,
            phone: order.customerPhone
          }],
          locationId: order.storeLocationId
        })
      }
    );

    const result = await response.json();
    console.log(`Survey queued for ${result.data.contactsProcessed} contact(s)`);
  }
  ```

  ```python Python - Bulk Execute theme={null}
  import requests

  # Execute for multiple customers
  contacts = [
      {'email': 'alice@example.com', 'firstName': 'Alice', 'phone': '+15551234567'},
      {'email': 'bob@example.com', 'firstName': 'Bob', 'phone': '+15559876543'},
      # ... up to 100 contacts
  ]

  response = requests.post(
      'https://app.demeterrr.com/api/v1/sequences/880e8400-e29b-41d4-a716-446655440000/execute',
      headers={
          'X-API-Key': 'dem_your_key_here',
          'Content-Type': 'application/json'
      },
      json={
          'contacts': contacts,
          'locationId': '660e8400-e29b-41d4-a716-446655440000'
      }
  )

  result = response.json()['data']
  print(f"Processed: {result['contactsProcessed']}, Queued: {result['sendingsCreated']}")
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "data": {
      "sequenceId": "880e8400-e29b-41d4-a716-446655440000",
      "sequenceName": "Post-Purchase Satisfaction Survey",
      "contactsProcessed": 2,
      "sendingsCreated": 2,
      "results": [
        {
          "email": "customer1@example.com",
          "contactId": "990e8400-e29b-41d4-a716-446655440000",
          "status": "queued"
        },
        {
          "email": "customer2@example.com",
          "contactId": "aa0e8400-e29b-41d4-a716-446655440000",
          "status": "queued"
        }
      ]
    }
  }
  ```

  ```json 400 Sequence Inactive theme={null}
  {
    "error": {
      "code": "SEQUENCE_INACTIVE",
      "message": "Sequence is not active"
    }
  }
  ```

  ```json 400 Validation Error theme={null}
  {
    "error": {
      "code": "VALIDATION_ERROR",
      "message": "Invalid request data",
      "details": {
        "contacts": ["At least one contact is required"],
        "contacts.0.email": ["Invalid email address"]
      }
    }
  }
  ```
</ResponseExample>

## Use Cases

<AccordionGroup>
  <Accordion title="Post-Purchase Surveys">
    Trigger CSAT or NPS surveys automatically after customers complete a purchase.

    ```javascript theme={null}
    executeSequence(satisfactionSequenceId, {
      contacts: [{ email: customer.email, firstName: customer.name }]
    });
    ```
  </Accordion>

  <Accordion title="Service Appointment Follow-up">
    Send review requests after service appointments (dental, salon, etc.).

    ```javascript theme={null}
    executeSequence(reviewSequenceId, {
      contacts: [{ email: appointment.customerEmail }],
      employeeId: appointment.providerId
    });
    ```
  </Accordion>

  <Accordion title="Onboarding Sequences">
    Welcome new customers with a multi-step onboarding sequence.

    ```javascript theme={null}
    executeSequence(onboardingSequenceId, {
      contacts: newSignups.map(user => ({
        email: user.email,
        firstName: user.firstName
      }))
    });
    ```
  </Accordion>

  <Accordion title="Bulk Campaign">
    Execute marketing campaigns for up to 100 contacts at once.

    ```javascript theme={null}
    // Process in batches of 100
    for (let i = 0; i < allContacts.length; i += 100) {
      const batch = allContacts.slice(i, i + 100);
      await executeSequence(campaignId, { contacts: batch });
    }
    ```
  </Accordion>
</AccordionGroup>
