Skip to main content

Prerequisites

Before you begin, make sure you have:
  1. Installed the SDK
  2. Set up your API key

Initialize the Client

Create a new client instance to start making API calls:
import BrewSDK from 'brew-sdk';

const client = new BrewSDK();
The client automatically uses the BREW_SDK_API_KEY environment variable for authentication.

Import Contacts

Import contacts into your Brew audience:
import BrewSDK from 'brew-sdk';

const client = new BrewSDK();

const result = await client.contacts.import.create({
  contacts: [
    {
      email: 'john@example.com',
      firstName: 'John',
      lastName: 'Doe',
      subscribed: true,
      customFields: {
        company: 'Acme Inc',
        role: 'Developer',
      },
    },
    {
      email: 'jane@example.com',
      firstName: 'Jane',
      lastName: 'Smith',
    },
  ],
});

console.log('Import results:', result.data.stats);
// { total: 2, valid: 2, invalid: 0 }

Update a Contact

Update an existing contact’s information:
const updated = await client.contacts.update({
  email: 'john@example.com',
  firstName: 'Johnny',
  customFields: {
    role: 'Senior Developer',
    department: 'Engineering',
  },
});

console.log('Contact updated:', updated.data);

Trigger an Automation

Trigger an automation workflow with a payload:
const result = await client.automations.trigger('auto_order_confirm', {
  email: 'customer@example.com',
  firstName: 'John',
  orderId: 'ORD-12345',
  orderTotal: 99.99,
});

console.log('Automation triggered:', result.executionId);
// exec_abc123
The payload is validated against the automation’s configured schema. Required fields must be present.

Send a Transactional Email

Send a transactional email using a published template:
const response = await client.send.transactional.send({
  chatId: 'your-template-id',
  to: 'user@example.com',
  variables: {
    firstName: 'John',
    orderNumber: 'ORD-12345',
    trackingUrl: 'https://example.com/track/xyz',
  },
});

console.log('Email sent:', response.data);
// { sent: 1, failed: 0, results: [...] }
You can also send to multiple recipients:
const response = await client.send.transactional.send({
  chatId: 'your-template-id',
  to: ['user1@example.com', 'user2@example.com'],
  variables: {
    announcement: 'New feature released!',
  },
});

Delete a Contact

Remove a contact from your audience:
const deleted = await client.contacts.delete({
  email: 'john@example.com',
});

console.log('Contact deleted:', deleted.data);
// { deleted: true, email: 'john@example.com' }

Working with Types

The SDK includes TypeScript definitions for all request parameters and response types:
import BrewSDK from 'brew-sdk';

const client = new BrewSDK();

// Use typed parameters
const params: BrewSDK.Contacts.ImportCreateParams = {
  contacts: [
    { email: 'john@example.com', firstName: 'John' },
  ],
};

// Get typed response
const result: BrewSDK.Contacts.ImportCreateResponse = 
  await client.contacts.import.create(params);

// Access typed data
console.log(result.data.stats?.total);
console.log(result.data.importId);

Handling Responses

All SDK methods return typed response objects:
const result = await client.contacts.import.create({
  contacts: [{ email: 'test@example.com' }],
});

// Check success
if (result.success) {
  console.log('Import ID:', result.data.importId);
  console.log('Stats:', result.data.stats);
  
  // Handle validation errors
  if (result.data.errors?.length) {
    result.data.errors.forEach(error => {
      console.log(`Error at index ${error.index}: ${error.error}`);
    });
  }
}

// Access metadata
console.log('Request ID:', result.meta?.requestId);

Error Handling

Wrap API calls in try-catch to handle errors:
import BrewSDK from 'brew-sdk';

const client = new BrewSDK();

try {
  const result = await client.contacts.import.create({
    contacts: [{ email: 'invalid-email' }],
  });
} catch (error) {
  if (error instanceof BrewSDK.BadRequestError) {
    console.error('Invalid request:', error.message);
  } else if (error instanceof BrewSDK.AuthenticationError) {
    console.error('Authentication failed - check your API key');
  } else if (error instanceof BrewSDK.RateLimitError) {
    console.error('Rate limited - slow down requests');
  } else {
    throw error;
  }
}
See Error Handling for more details.

Complete Example

Here’s a complete example putting it all together:
import BrewSDK from 'brew-sdk';

async function main() {
  const client = new BrewSDK();

  try {
    // Import a new contact
    const importResult = await client.contacts.import.create({
      contacts: [
        {
          email: 'newuser@example.com',
          firstName: 'New',
          lastName: 'User',
          customFields: {
            source: 'api-quickstart',
          },
        },
      ],
    });

    console.log('Imported:', importResult.data.stats);

    // Send welcome email
    const emailResult = await client.send.transactional.send({
      chatId: 'welcome-email-template',
      to: 'newuser@example.com',
      variables: {
        firstName: 'New',
        dashboardUrl: 'https://app.example.com/dashboard',
      },
    });

    console.log('Welcome email sent:', emailResult.data.sent);

  } catch (error) {
    if (error instanceof BrewSDK.APIError) {
      console.error('API Error:', error.status, error.message);
    } else {
      throw error;
    }
  }
}

main();

Next Steps

Contacts

Learn more about managing contacts

Transactional Emails

Send transactional emails

Error Handling

Handle errors and configure retries

API Reference

View the full API documentation

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.