Welcome to the Contactlist, let's grow together!

ContactList
ContactListNumletive

Advanced Examples

These advanced examples demonstrate more complex use cases and patterns for working with ContactList.

Batch Operations

Create multiple contacts in a single request:

async function createBatchContacts(contacts) {
  const response = await fetch(
    'https://api.contactlist.io/v1/contacts/batch',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.CONTACTLIST_API_KEY}`
      },
      body: JSON.stringify({ contacts })
    }
  );

  if (!response.ok) {
    throw new Error(`Failed to create contacts: ${response.statusText}`);
  }

  return await response.json();
}

// Usage
const contacts = [
  { name: 'John Doe', email: 'john@example.com' },
  { name: 'Jane Smith', email: 'jane@example.com' },
  { name: 'Bob Johnson', email: 'bob@example.com' }
];

const result = await createBatchContacts(contacts);
console.log(`Created ${result.created} contacts`);

Searching Contacts

Search contacts by various criteria:

async function searchContacts(query, filters = {}) {
  const params = new URLSearchParams({
    q: query,
    ...filters
  });

  const response = await fetch(
    `https://api.contactlist.io/v1/contacts/search?${params}`,
    {
      headers: {
        'Authorization': `Bearer ${process.env.CONTACTLIST_API_KEY}`
      }
    }
  );

  if (!response.ok) {
    throw new Error(`Search failed: ${response.statusText}`);
  }

  return await response.json();
}

// Usage
const results = await searchContacts('john', {
  tag: 'customer',
  limit: 20
});

Webhook Handling

Set up webhooks to receive real-time updates:

// Express.js example
app.post('/webhooks/contactlist', async (req, res) => {
  const { event, data } = req.body;

  try {
    switch (event) {
      case 'contact.created':
        await handleContactCreated(data);
        break;
      case 'contact.updated':
        await handleContactUpdated(data);
        break;
      case 'contact.deleted':
        await handleContactDeleted(data);
        break;
      default:
        console.log('Unknown event:', event);
    }

    res.status(200).json({ received: true });
  } catch (error) {
    console.error('Webhook error:', error);
    res.status(500).json({ error: 'Processing failed' });
  }
});

async function handleContactCreated(contact) {
  console.log('New contact created:', contact);
  // Your logic here
}

async function handleContactUpdated(contact) {
  console.log('Contact updated:', contact);
  // Your logic here
}

async function handleContactDeleted(contactId) {
  console.log('Contact deleted:', contactId);
  // Your logic here
}

Error Handling with Retries

Implement robust error handling with exponential backoff:

async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url, options);
      
      if (response.ok) {
        return await response.json();
      }

      // Retry on 5xx errors
      if (response.status >= 500 && i < maxRetries - 1) {
        const delay = Math.pow(2, i) * 1000; // Exponential backoff
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }

      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

// Usage
try {
  const contacts = await fetchWithRetry(
    'https://api.contactlist.io/v1/contacts',
    {
      headers: {
        'Authorization': `Bearer ${process.env.CONTACTLIST_API_KEY}`
      }
    }
  );
} catch (error) {
  console.error('Failed after retries:', error);
}

Rate Limit Handling

Handle rate limits gracefully:

async function fetchWithRateLimit(url, options) {
  const response = await fetch(url, options);
  
  const rateLimitRemaining = parseInt(
    response.headers.get('X-RateLimit-Remaining') || '0'
  );
  const rateLimitReset = parseInt(
    response.headers.get('X-RateLimit-Reset') || '0'
  );

  if (response.status === 429) {
    const waitTime = (rateLimitReset * 1000) - Date.now();
    console.log(`Rate limited. Waiting ${waitTime}ms`);
    await new Promise(resolve => setTimeout(resolve, Math.max(waitTime, 0)));
    return fetchWithRateLimit(url, options); // Retry
  }

  if (rateLimitRemaining < 10) {
    console.warn(`Rate limit low: ${rateLimitRemaining} remaining`);
  }

  return response;
}

Tip: Always implement proper error handling and retry logic in production applications to ensure reliability.

Next Steps

For more information, check out our API Reference or Best Practices guide.