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!
Before we jump in, make sure you've got these essentials:
Let's kick things off:
mkdir affinity-api-integration cd affinity-api-integration npm init -y npm install axios dotenv
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;
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); } }
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; }
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'); }
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); });
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!