CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-twilio

A comprehensive Node.js SDK for the Twilio communications platform, enabling SMS, voice, video, and other communication services integration.

Pending
Overview
Eval results
Files

rest-client.mddocs/

REST API Client

The Twilio REST API Client provides access to all Twilio services through a unified interface. The main Twilio class serves as the entry point to 38+ service domains, each containing resources and methods for specific Twilio functionality.

Capabilities

Twilio Constructor

Creates a new Twilio REST API client instance with authentication and configuration options.

/**
 * Creates a new Twilio REST API client instance
 * @param username - Account SID or API Key SID for authentication
 * @param password - Auth Token or API Key Secret for authentication  
 * @param opts - Configuration options for the client
 * @returns A new Twilio client instance
 */
constructor(username?: string, password?: string, opts?: ClientOpts);

interface ClientOpts {
  /** Custom HTTP client for requests */
  httpClient?: RequestClient;
  /** Override account SID (for API key authentication) */
  accountSid?: string;
  /** Environment variables (alternative to process.env) */
  env?: NodeJS.ProcessEnv;
  /** Twilio edge location for requests */
  edge?: string;
  /** Twilio region for requests */
  region?: string;
  /** Enable lazy loading of service domains (default: true) */
  lazyLoading?: boolean;
  /** Logging level for debug information */
  logLevel?: string;
  /** Additional user agent extensions */
  userAgentExtensions?: string[];
  /** Enable automatic request retries (default: false) */
  autoRetry?: boolean;
  /** Maximum retry delay in milliseconds */
  maxRetryDelay?: number;
  /** Maximum number of retry attempts */
  maxRetries?: number;
  /** Validation client configuration */
  validationClient?: ValidationClientOptions;
  /** Request timeout in milliseconds */
  timeout?: number;
  /** Enable HTTP Keep-Alive */
  keepAlive?: boolean;
  /** Keep-Alive timeout in milliseconds */
  keepAliveMsecs?: number;
  /** Maximum number of sockets per host */
  maxSockets?: number;
  /** Maximum total number of sockets */
  maxTotalSockets?: number;
  /** Maximum number of free sockets */
  maxFreeSockets?: number;
  /** Socket scheduling algorithm */
  scheduling?: "fifo" | "lifo" | undefined;
  /** Certificate Authority for HTTPS requests */
  ca?: string | Buffer;
}

Usage Examples:

import TwilioSDK from "twilio";

// Basic authentication with Account SID and Auth Token
const client = TwilioSDK("AC123...", "auth_token_here");

// API Key authentication
const client = TwilioSDK("SK456...", "api_secret_here", {
  accountSid: "AC123..."
});

// Environment variable authentication
const client = TwilioSDK(); // Uses TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN

// Advanced configuration
const client = TwilioSDK("AC123...", "auth_token", {
  region: "sydney",
  edge: "au1", 
  autoRetry: true,
  maxRetries: 3,
  timeout: 30000,
  logLevel: "debug"
});

Core API Domain (api)

The main Twilio REST API v2010 domain containing core communication resources.

/** Core Twilio REST API v2010 domain */
api: Api;

interface Api {
  /** Account management and configuration */
  account: AccountContext;
  accounts: AccountListInstance;
  
  // Legacy direct access (deprecated - use account.* instead)
  addresses: AddressListInstance;
  applications: ApplicationListInstance;
  calls: CallListInstance;
  conferences: ConferenceListInstance;
  incomingPhoneNumbers: IncomingPhoneNumberListInstance;
  keys: KeyListInstance;
  messages: MessageListInstance;
  notifications: NotificationListInstance;
  outgoingCallerIds: OutgoingCallerIdListInstance;
  queues: QueueListInstance;
  recordings: RecordingListInstance;
  shortCodes: ShortCodeListInstance;
  signingKeys: SigningKeyListInstance;
  tokens: TokenListInstance;
  transcriptions: TranscriptionListInstance;
  usage: UsageListInstance;
}

Communication Service Domains

Service domains for various communication channels and capabilities.

/** Messaging services and templates */
messaging: Messaging;

/** Voice services and applications */
voice: Voice;

/** Video communications and rooms */
video: Video;

/** Chat services (legacy - use conversations instead) */
chat: Chat;

/** Modern conversations API */
conversations: Conversations;

/** IP Messaging services (legacy) */
ipMessaging: IpMessaging;

Platform and Infrastructure Services

Core platform services for application infrastructure and management.

/** Real-time data synchronization */
sync: Sync;

/** Contact center and workforce management */
taskrouter: Taskrouter;

/** Visual workflow builder */
studio: Studio;

/** Serverless functions and assets */
serverless: Serverless;

/** Multi-channel notifications */
notify: Notify;

/** Phone number lookup and validation */
lookups: Lookups;

/** Usage and billing insights */
insights: Insights;

/** Call and message monitoring */
monitor: Monitor;

/** Pricing information for services */
pricing: Pricing;

Security and Authentication Services

Services for authentication, verification, and security compliance.

/** Two-factor authentication and verification */
verify: Verify;

/** Identity and access management */
iam: Iam;

/** OAuth authentication services */
oauth: Oauth;

/** Regulatory compliance and trust */
trusthub: Trusthub;

/** Preview IAM features */
previewIam: PreviewIam;

Specialized Service Domains

Domain-specific services for specialized use cases.

/** IoT connectivity with Super SIM */
supersim: Supersim;

/** Wireless connectivity management */
wireless: Wireless;

/** SIP trunking services */
trunking: Trunking;

/** Anonymous communications */
proxy: Proxy;

/** Phone number routing and management */
routes: Routes;

/** Phone number management */
numbers: Numbers;

/** Content management and templates */
content: Content;

/** Marketplace integrations */
marketplace: Marketplace;

/** Events and webhooks */
events: Events;

/** AI and machine learning services */
intelligence: Intelligence;

/** AI assistants and automation */
assistants: Assistants;

/** Contact center operations */
flexApi: FlexApi;

/** Customer engagement platform */
frontlineApi: FrontlineApi;

/** Data export services */
bulkexports: Bulkexports;

/** Account and sub-account management */
accounts: Accounts;

/** Preview and experimental features */
preview: Preview;

Request Method

Low-level request method for direct API calls with full control over HTTP parameters.

/**
 * Makes a request to the Twilio API using the configured HTTP client
 * @param opts - Request configuration options
 * @returns Promise resolving to the API response
 */
request(opts: RequestOpts): Promise<any>;

interface RequestOpts {
  /** HTTP method for the request */
  method?: HttpMethod;
  /** Full URI for the API endpoint */
  uri?: string;
  /** Username for authentication (overrides client default) */
  username?: string;
  /** Password for authentication (overrides client default) */
  password?: string;
  /** Custom authentication strategy */
  authStrategy?: AuthStrategy;
  /** HTTP headers for the request */
  headers?: Headers;
  /** Query parameters for GET requests */
  params?: object;
  /** Request body data for POST/PUT requests */
  data?: object;
  /** Request timeout in milliseconds */
  timeout?: number;
  /** Allow HTTP redirects */
  allowRedirects?: boolean;
  /** Log level for this specific request */
  logLevel?: string;
}

type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "PATCH";

interface Headers {
  [key: string]: string;
}

Usage Examples:

// Direct API call example
const response = await client.request({
  method: "POST",
  uri: "https://api.twilio.com/2010-04-01/Accounts/AC123.../Messages.json",
  data: {
    From: "+1234567890",
    To: "+0987654321", 
    Body: "Hello from Twilio!"
  }
});

// Custom headers and authentication
const response = await client.request({
  method: "GET",
  uri: "https://api.twilio.com/2010-04-01/Accounts/AC123.../Calls.json",
  headers: {
    "Accept": "application/json",
    "Custom-Header": "value"
  },
  params: {
    Status: "completed",
    PageSize: 50
  }
});

SSL Certificate Validation

Utility method to test SSL certificate compatibility.

/**
 * Test SSL certificate compatibility by making a request to Twilio's test endpoint
 * @throws RestException if the SSL test fails
 * @returns Promise resolving to the test response
 */
validateSslCert(): Promise<any>;

Common Resource Patterns

All Twilio resources follow consistent patterns for CRUD operations.

// List resources (with pagination)
interface ListInstance<T> {
  create(params: CreateParams): Promise<T>;
  list(params?: ListParams): Promise<T[]>;
  page(params?: PageParams): Promise<Page<T>>;
  each(callback: (item: T) => void, done?: () => void): void;
  each(params: EachParams, callback: (item: T) => void, done?: () => void): void;
}

// Individual resource context
interface Context<T> {
  fetch(): Promise<T>;
  update(params: UpdateParams): Promise<T>;
  remove(): Promise<boolean>;
}

// Pagination support
interface Page<T> {
  instances: T[];
  nextPageUrl?: string;
  previousPageUrl?: string;
  meta: PageMeta;
}

interface PageMeta {
  page: number;
  pageSize: number;
  firstPageUrl: string;
  nextPageUrl?: string;
  previousPageUrl?: string;
  url: string;
  key: string;
}

Usage Examples:

// Creating resources
const message = await client.messages.create({
  body: "Hello World",
  from: "+1234567890", 
  to: "+0987654321"
});

const call = await client.calls.create({
  url: "http://demo.twilio.com/docs/voice.xml",
  from: "+1234567890",
  to: "+0987654321"
});

// Fetching individual resources
const message = await client.messages("MM123...").fetch();
const call = await client.calls("CA456...").fetch();

// Updating resources
const updatedCall = await client.calls("CA456...").update({
  status: "completed"
});

// Listing resources with pagination
const messages = await client.messages.list({
  from: "+1234567890",
  dateSentAfter: new Date("2023-01-01")
});

// Iterating through all resources
client.messages.each({
  from: "+1234567890",
  pageSize: 100
}, (message) => {
  console.log(message.sid, message.body);
});

Types

interface ValidationClientOptions {
  /** Enable request validation */
  enabled?: boolean;
  /** Validation timeout in milliseconds */
  timeout?: number;
}

interface AuthStrategy {
  /** Apply authentication to the request */
  apply(request: RequestConfig): Promise<RequestConfig>;
}

interface RequestConfig {
  method: HttpMethod;
  url: string;
  headers: Headers;
  data?: any;
  timeout?: number;
}

Install with Tessl CLI

npx tessl i tessl/npm-twilio

docs

credential-providers.md

index.md

jwt.md

rest-client.md

twiml.md

webhooks.md

tile.json