Back

Step by Step Guide to Building a lemlist API Integration in JS

Aug 14, 20246 minute read

Introduction

Hey there, fellow developer! Ready to supercharge your outreach game with lemlist's API? Let's dive in and build a slick integration that'll have you automating campaigns like a pro. We'll cover everything from basic setup to some nifty advanced features, so buckle up!

Prerequisites

Before we get our hands dirty, make sure you've got:

  • Node.js and npm (you're probably way ahead of me on this one)
  • A lemlist API key (if you don't have one, hop over to your lemlist account and grab it)
  • Your HTTP request library of choice (Axios is my go-to, but fetch works great too)

Setting up the project

Let's kick things off:

mkdir lemlist-integration && cd lemlist-integration npm init -y npm install axios dotenv

Create a .env file for your API key:

LEMLIST_API_KEY=your_api_key_here

Authentication

Time to get that API key working for us. Create an api.js file:

require('dotenv').config(); const axios = require('axios'); const api = axios.create({ baseURL: 'https://api.lemlist.com/api', headers: { 'Authorization': `Bearer ${process.env.LEMLIST_API_KEY}` } }); module.exports = api;

Basic API Requests

Let's fetch some campaigns and create a lead:

const api = require('./api'); // Get campaigns async function getCampaigns() { try { const response = await api.get('/campaigns'); console.log(response.data); } catch (error) { console.error('Error fetching campaigns:', error.response.data); } } // Create a lead async function createLead(campaignId, leadData) { try { const response = await api.post(`/campaigns/${campaignId}/leads`, leadData); console.log('Lead created:', response.data); } catch (error) { console.error('Error creating lead:', error.response.data); } } getCampaigns(); createLead('campaign_id', { email: '[email protected]', firstName: 'John' });

Handling Responses

As you've seen, we're using try/catch blocks to handle errors gracefully. Always check error.response.data for detailed error messages from lemlist.

Advanced Features

Pagination

lemlist uses cursor-based pagination. Here's how to handle it:

async function getAllCampaigns() { let cursor = null; let allCampaigns = []; do { const response = await api.get('/campaigns', { params: { cursor } }); allCampaigns = allCampaigns.concat(response.data.data); cursor = response.data.next; } while (cursor); return allCampaigns; }

Filtering and Sorting

Many endpoints support filtering and sorting. For example:

api.get('/campaigns', { params: { sort: 'createdAt:desc', filter: 'status:active' } });

Webhooks

lemlist can send webhooks for various events. Here's a quick Express server to handle them:

const express = require('express'); const app = express(); app.use(express.json()); app.post('/webhook', (req, res) => { const event = req.body; console.log('Received webhook:', event); // Process the event res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));

Best Practices

  • Respect rate limits: lemlist has rate limits, so implement exponential backoff for retries.
  • Cache responses when appropriate to reduce API calls.
  • Use environment variables for sensitive data like API keys.

Testing

Here's a quick Jest test to get you started:

jest.mock('./api'); const api = require('./api'); test('getCampaigns fetches campaigns successfully', async () => { api.get.mockResolvedValue({ data: [{ id: '1', name: 'Test Campaign' }] }); const campaigns = await getCampaigns(); expect(campaigns).toHaveLength(1); expect(campaigns[0].name).toBe('Test Campaign'); });

Conclusion

And there you have it! You're now armed with the knowledge to build a robust lemlist API integration. Remember, the API docs are your best friend for diving deeper into specific endpoints and features.

Now go forth and automate those campaigns like a boss! Happy coding! 🚀