Twilio API API in JavaScript

Twilio API API in JavaScript

This guide shows you how to integrate the Twilio API into your JavaScript application. SMS, Voice, WhatsApp, Video, and Verify APIs for omnichannel customer engagement.

Prerequisites

  • JavaScript installed on your system
  • An Twilio API API key (sign up at https://twilio.com)
  • Basic familiarity with HTTP APIs

Installation

npm install node-fetch
# or use built-in fetch in Node 18+

Basic Usage

const API_KEY = process.env.API_KEY || 'YOUR_API_KEY';
const BASE_URL = 'https://api.twilio.com';

async function callApi() {
  const response = await fetch(`${BASE_URL}/v1/resources`, {
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    }
  });
  const data = await response.json();
  console.log('Status:', response.status);
  console.log(data);
  return data;
}

callApi().catch(console.error);

Error Handling

async function callApiWithRetry(url, options, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);
      if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
        console.log(`Rate limited. Waiting ${retryAfter}s...`);
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        continue;
      }
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      return await response.json();
    } catch (error) {
      console.error(`Attempt ${attempt + 1} failed:`, error.message);
      if (attempt === maxRetries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
    }
  }
}

callApiWithRetry(`${BASE_URL}/v1/resources`, {
  headers: { 'Authorization': `Bearer ${API_KEY}` }
}).then(console.log).catch(console.error);

Advanced Usage

class TwilioClient {
  constructor(apiKey, baseUrl = 'https://api.twilio.com') {
    this.apiKey = apiKey;
    this.baseUrl = baseUrl.replace(/\/$/, '');
  }

  async request(method, path, options = {}) {
    const url = `${this.baseUrl}/v1${path}`;
    const response = await fetch(url, {
      method,
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
        ...options.headers
      },
      body: options.body ? JSON.stringify(options.body) : undefined,
      ...options
    });
    if (!response.ok) {
      const error = await response.json().catch(() => ({}));
      throw new Error(`API Error: ${error.message || response.statusText}`);
    }
    return response.json();
  }

  async listResources(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.request('GET', `/resources${query ? '?' + query : ''}`);
  }

  async createResource(data) {
    return this.request('POST', '/resources', { body: data });
  }

  async getResource(id) {
    return this.request('GET', `/resources/${id}`);
  }
}

const client = new TwilioClient(process.env.API_KEY);
client.listResources({ limit: 50 })
  .then(data => console.log(`Found ${data.data.length} resources`))
  .catch(console.error);

Best Practices

  • Store your API key in an environment variable, never in source code
  • Implement retry logic with exponential backoff for 429 and 5xx errors
  • Set reasonable timeouts (10-30 seconds) for all API calls
  • Log request IDs from response headers for debugging
  • Cache responses where appropriate to reduce API calls

Other languages