Best practices for integrating IntentGPT B2B Intent API
# .env file INTENTGPT_API_KEY=p1rOh.your.api.key
// Load environment variables require('dotenv').config(); const apiKey = process.env.INTENTGPT_API_KEY;
async function getIntent() { try { const response = await fetch('https://api.intentgpt.ai/intent', { headers: { 'x-api-key': process.env.INTENTGPT_API_KEY } }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error('API Error:', error); // Handle specific error cases if (error.status === 401) { // Handle authentication error } else if (error.status === 429) { // Handle rate limit error } throw error; } }
async function getAllIntent(params = {}) { let allResults = []; let offset = 0; const LIMIT = 1000; // API returns max 1000 rows while (true) { const response = await fetch(`https://api.intentgpt.ai/intent?offset=${offset}`, { headers: { 'x-api-key': process.env.INTENTGPT_API_KEY } }); const data = await response.json(); allResults = allResults.concat(data); if (data.length < LIMIT) { break; // No more results } offset += LIMIT; } return allResults; }
const NodeCache = require('node-cache'); const cache = new NodeCache({ stdTTL: 300 }); // 5 minutes cache async function getCachedIntent(params) { const cacheKey = JSON.stringify(params); const cached = cache.get(cacheKey); if (cached) { return cached; } const response = await fetch('https://api.intentgpt.ai/intent', { headers: { 'x-api-key': process.env.INTENTGPT_API_KEY }, params }); const data = await response.json(); cache.set(cacheKey, data); return data; }
function validateParams(params) { const validIntentLevels = ['ONFIRE', 'HOT', 'WARM', 'COLD']; if (params.intent_levels) { const levels = params.intent_levels.split(','); const invalidLevels = levels.filter(level => !validIntentLevels.includes(level)); if (invalidLevels.length > 0) { throw new Error(`Invalid intent levels: ${invalidLevels.join(', ')}`); } } if (params.companies) { const companies = params.companies.split(','); companies.forEach(company => { if (!company.includes('.')) { throw new Error(`Invalid company domain: ${company}`); } }); } return params; }
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 response; } if (response.status === 429) { const waitTime = Math.pow(2, i) * 1000; await new Promise(resolve => setTimeout(resolve, waitTime)); continue; } throw new Error(`HTTP error! status: ${response.status}`); } catch (error) { if (i === maxRetries - 1) throw error; } } }
const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const { intent_level, company, topic } = req.body; // Process intent update console.log(`New intent signal: ${company} - ${intent_level} for ${topic}`); // Update your system updateIntentData(req.body); res.status(200).send('Webhook received'); });
describe('IntentGPT API', () => { test('fetches intent data successfully', async () => { const response = await getIntent({ companies: 'example.com', topics: 'marketing', intent_levels: 'HOT' }); expect(response).toBeDefined(); expect(Array.isArray(response)).toBe(true); }); test('handles invalid API key', async () => { process.env.INTENTGPT_API_KEY = 'invalid_key'; await expect(getIntent()) .rejects .toThrow('Authentication failed'); }); });
const winston = require('winston'); const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: 'intent-api.log' }) ] }); async function loggedIntentFetch(params) { const startTime = Date.now(); try { const result = await getIntent(params); logger.info('API call successful', { params, duration: Date.now() - startTime, resultCount: result.length }); return result; } catch (error) { logger.error('API call failed', { params, error: error.message, duration: Date.now() - startTime }); throw error; } }
API Returns Empty Results
Authentication Issues