Hey there, fellow JavaScript aficionado! Ready to dive into the world of Typeform API integration? Let's get our hands dirty with some code and explore how to sync data for a user-facing integration. Buckle up!
Typeform's API is a powerful tool that lets you tap into the wealth of data from your forms. Whether you're building a custom dashboard or integrating form responses into your app, this API has got you covered.
First things first, you'll need to grab your API credentials. Head over to your Typeform account, navigate to the API section, and generate a personal access token. Once you've got that, let's set up authentication in your JavaScript code:
const axios = require('axios'); const typeformAPI = axios.create({ baseURL: 'https://api.typeform.com', headers: { 'Authorization': `Bearer ${YOUR_ACCESS_TOKEN}` } });
Now that we're authenticated, let's fetch some form responses:
async function getResponses(formId) { try { const response = await typeformAPI.get(`/forms/${formId}/responses`); return response.data.items; } catch (error) { console.error('Error fetching responses:', error); } }
Sometimes you need to submit responses programmatically. Here's how you can do that:
async function submitResponse(formId, answers) { try { await typeformAPI.post(`/forms/${formId}/responses`, { answers }); console.log('Response submitted successfully'); } catch (error) { console.error('Error submitting response:', error); } }
To keep your data in sync, you'll want to set up a webhook listener. Here's a quick Express.js example:
const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const { form_response } = req.body; // Process the form_response data console.log('New response received:', form_response); res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook listener running on port 3000'));
The Typeform API has rate limits, so let's implement some basic error handling and rate limiting:
const rateLimit = require('axios-rate-limit'); const typeformAPI = rateLimit(axios.create({ baseURL: 'https://api.typeform.com', headers: { 'Authorization': `Bearer ${YOUR_ACCESS_TOKEN}` } }), { maxRequests: 1, perMilliseconds: 1000 }); // In your API calls try { // Your API call here } catch (error) { if (error.response && error.response.status === 429) { console.log('Rate limit exceeded. Retrying after a delay...'); // Implement retry logic here } else { console.error('API error:', error.message); } }
To keep things snappy, consider implementing caching:
const NodeCache = require('node-cache'); const cache = new NodeCache({ stdTTL: 600 }); // Cache for 10 minutes async function getCachedResponses(formId) { const cacheKey = `responses_${formId}`; let responses = cache.get(cacheKey); if (!responses) { responses = await getResponses(formId); cache.set(cacheKey, responses); } return responses; }
Remember to keep your API credentials secure! Never expose them in client-side code. Use environment variables or a secure key management system.
Always test your API interactions. Here's a quick Jest test example:
test('getResponses fetches data correctly', async () => { const mockResponses = [{ id: '1', answers: [] }]; axios.get.mockResolvedValue({ data: { items: mockResponses } }); const responses = await getResponses('test-form-id'); expect(responses).toEqual(mockResponses); });
And there you have it! You're now equipped to read and write data like a pro using the Typeform API. Remember, the key to mastering any API is practice and exploration. Don't be afraid to experiment and push the boundaries of what you can do.
Happy coding, and may your integrations be ever smooth and your data always in sync!