Back

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

Aug 14, 20246 minute read

Introduction

Hey there, fellow developer! Ready to supercharge your outreach game with lemlist? You're in the right place. We're going to walk through building a Python integration with the lemlist API. This powerhouse combo will let you automate your campaigns, manage leads, and take your email sequences to the next level. Let's dive in!

Prerequisites

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

  • Python 3.7+
  • requests library (we'll use this for API calls)
  • Your lemlist API key (grab this from your account settings)

Setting up the environment

First things first, let's get our environment ready:

pip install requests

Now, let's keep our API key safe:

import os os.environ['LEMLIST_API_KEY'] = 'your_api_key_here'

Basic API Connection

Time to create our base API client:

import requests class LemlistClient: BASE_URL = 'https://api.lemlist.com/api' def __init__(self): self.api_key = os.environ.get('LEMLIST_API_KEY') self.session = requests.Session() self.session.headers.update({'Authorization': f'Bearer {self.api_key}'}) def _request(self, method, endpoint, **kwargs): url = f"{self.BASE_URL}/{endpoint}" response = self.session.request(method, url, **kwargs) response.raise_for_status() return response.json()

Core API Functionalities

Campaigns

Let's add some methods to manage campaigns:

def list_campaigns(self): return self._request('GET', 'campaigns') def create_campaign(self, name, team_id): data = {'name': name, 'teamId': team_id} return self._request('POST', 'campaigns', json=data) def update_campaign(self, campaign_id, **kwargs): return self._request('PATCH', f'campaigns/{campaign_id}', json=kwargs)

Leads

Now for some lead management:

def add_lead(self, campaign_id, email, **kwargs): data = {'email': email, **kwargs} return self._request('POST', f'campaigns/{campaign_id}/leads', json=data) def get_lead(self, campaign_id, lead_id): return self._request('GET', f'campaigns/{campaign_id}/leads/{lead_id}') def update_lead_status(self, campaign_id, lead_id, status): data = {'status': status} return self._request('PATCH', f'campaigns/{campaign_id}/leads/{lead_id}', json=data)

Sequences

Let's not forget about email sequences:

def get_sequences(self, campaign_id): return self._request('GET', f'campaigns/{campaign_id}/sequences') def schedule_email(self, campaign_id, lead_id, sequence_id, send_at): data = {'sendAt': send_at} return self._request('POST', f'campaigns/{campaign_id}/leads/{lead_id}/sequences/{sequence_id}/schedule', json=data)

Error Handling and Rate Limiting

Let's add some resilience to our client:

import time from requests.exceptions import RequestException def _request(self, method, endpoint, max_retries=3, **kwargs): for attempt in range(max_retries): try: response = self.session.request(method, f"{self.BASE_URL}/{endpoint}", **kwargs) response.raise_for_status() return response.json() except RequestException as e: if attempt == max_retries - 1: raise time.sleep(2 ** attempt) # Exponential backoff

Advanced Features

Webhook Integration

Want to receive real-time updates? Let's set up a webhook:

def create_webhook(self, url, events): data = {'url': url, 'events': events} return self._request('POST', 'webhooks', json=data)

Bulk Operations

For those times when you need to add multiple leads at once:

def bulk_add_leads(self, campaign_id, leads): return self._request('POST', f'campaigns/{campaign_id}/leads/bulk', json=leads)

Testing the Integration

Don't forget to test! Here's a quick example using unittest:

import unittest from unittest.mock import patch from your_module import LemlistClient class TestLemlistClient(unittest.TestCase): @patch('your_module.requests.Session') def test_list_campaigns(self, mock_session): mock_session().request.return_value.json.return_value = {'campaigns': []} client = LemlistClient() result = client.list_campaigns() self.assertEqual(result, {'campaigns': []})

Best Practices

  1. Keep your API key secure. Never commit it to version control.
  2. Use environment variables or a secure config file for sensitive data.
  3. Implement proper error handling and logging.
  4. Respect rate limits to avoid getting your requests blocked.

Conclusion

And there you have it! You've just built a robust lemlist API integration in Python. With this foundation, you can automate your outreach campaigns, manage leads effortlessly, and take your email game to new heights.

Remember, this is just the beginning. The lemlist API has even more features to explore, so don't be afraid to dive deeper and customize this integration to fit your specific needs.

Happy coding, and may your open rates be ever in your favor! 🚀📧