Back

Step by Step Guide to Building an Affinity API Integration in JS

Aug 18, 20247 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of Affinity API integration? You're in for a treat. Affinity's API is a powerhouse for managing relationships and data, and we're about to harness that power with some JavaScript magic. Let's get cracking!

Prerequisites

Before we jump in, make sure you've got these essentials:

  • Node.js and npm (you're probably nodding already)
  • An Affinity API key (if you don't have one, go grab it from your Affinity account)
  • Axios or your favorite HTTP client (we'll use Axios in this guide)

Setting up the project

Let's kick things off:

mkdir affinity-api-integration cd affinity-api-integration npm init -y npm install axios dotenv

Authentication

First things first, let's keep that API key safe:

// .env AFFINITY_API_KEY=your_api_key_here

Now, let's create our API client:

// affinityClient.js require('dotenv').config(); const axios = require('axios'); const affinityClient = axios.create({ baseURL: 'https://api.affinity.co/api/v1', headers: { 'Authorization': `Basic ${Buffer.from(process.env.AFFINITY_API_KEY + ':').toString('base64')}`, 'Content-Type': 'application/json' } }); module.exports = affinityClient;

Basic API Requests

Time to make some requests! Here's a quick GET and POST:

const affinityClient = require('./affinityClient'); // GET request async function getLists() { try { const response = await affinityClient.get('/lists'); console.log(response.data); } catch (error) { console.error('Error fetching lists:', error.response.data); } } // POST request async function createPerson(personData) { try { const response = await affinityClient.post('/persons', personData); console.log('Person created:', response.data); } catch (error) { console.error('Error creating person:', error.response.data); } }

Implementing Key Affinity API Features

Let's tackle some core features:

// Fetch lists async function fetchLists() { const response = await affinityClient.get('/lists'); return response.data; } // Manage persons async function updatePerson(personId, updateData) { const response = await affinityClient.put(`/persons/${personId}`, updateData); return response.data; } // Handle organizations async function createOrganization(orgData) { const response = await affinityClient.post('/organizations', orgData); return response.data; } // Work with notes async function addNote(entityType, entityId, content) { const response = await affinityClient.post('/notes', { entity_type: entityType, entity_id: entityId, content: content }); return response.data; }

Pagination and Rate Limiting

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

async function getAllLists() { let allLists = []; let cursor = null; do { const response = await affinityClient.get('/lists', { params: { cursor: cursor } }); allLists = allLists.concat(response.data.lists); cursor = response.data.next_cursor; } while (cursor); return allLists; }

For rate limiting, implement exponential backoff:

async function makeRequestWithBackoff(requestFn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await requestFn(); } catch (error) { if (error.response && error.response.status === 429) { const delay = Math.pow(2, i) * 1000; await new Promise(resolve => setTimeout(resolve, delay)); } else { throw error; } } } throw new Error('Max retries reached'); }

Best Practices

  • Always handle errors gracefully
  • Log important operations and errors
  • Use environment variables for sensitive data
  • Implement request throttling to respect API limits

Testing

Here's a quick example using Jest:

jest.mock('./affinityClient'); test('fetchLists returns list data', async () => { const mockData = { lists: [{ id: 1, name: 'Test List' }] }; affinityClient.get.mockResolvedValue({ data: mockData }); const result = await fetchLists(); expect(result).toEqual(mockData); });

Deployment Considerations

  • Use environment variables in production
  • Securely manage your API keys (consider using a secrets manager)
  • Implement proper error handling and logging for production environments

Conclusion

And there you have it! You've just built a solid foundation for your Affinity API integration. Remember, this is just the beginning – there's so much more you can do with Affinity's API. Keep exploring, keep building, and most importantly, keep having fun with it!

For more details, check out the Affinity API documentation. Happy coding!