Development Best Practices

API Key Management

Store your API key securely using environment variables:

# .env file
INTENTGPT_API_KEY=p1rOh.your.api.key
// Load environment variables
require('dotenv').config();

const apiKey = process.env.INTENTGPT_API_KEY;

Error Handling

Implement robust error handling in your API calls:

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;
  }
}

Pagination Implementation

Handle pagination for large datasets:

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;
}

Caching Strategy

Implement caching to optimize API usage:

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;
}

Parameter Validation

Validate parameters before making API calls:

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;
}

Rate Limit Handling

Implement rate limit 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 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;
    }
  }
}

Webhook Implementation

Set up webhooks to receive real-time updates:

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');
});

Testing

API Testing

Use Jest for testing API integration:

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');
  });
});

Monitoring

Logging Implementation

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;
  }
}

Troubleshooting

Support Resources

For enterprise support and custom integration assistance, contact our team at enterprise@intentgpt.ai