0
# REST API Client
1
2
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.
3
4
## Capabilities
5
6
### Twilio Constructor
7
8
Creates a new Twilio REST API client instance with authentication and configuration options.
9
10
```typescript { .api }
11
/**
12
* Creates a new Twilio REST API client instance
13
* @param username - Account SID or API Key SID for authentication
14
* @param password - Auth Token or API Key Secret for authentication
15
* @param opts - Configuration options for the client
16
* @returns A new Twilio client instance
17
*/
18
constructor(username?: string, password?: string, opts?: ClientOpts);
19
20
interface ClientOpts {
21
/** Custom HTTP client for requests */
22
httpClient?: RequestClient;
23
/** Override account SID (for API key authentication) */
24
accountSid?: string;
25
/** Environment variables (alternative to process.env) */
26
env?: NodeJS.ProcessEnv;
27
/** Twilio edge location for requests */
28
edge?: string;
29
/** Twilio region for requests */
30
region?: string;
31
/** Enable lazy loading of service domains (default: true) */
32
lazyLoading?: boolean;
33
/** Logging level for debug information */
34
logLevel?: string;
35
/** Additional user agent extensions */
36
userAgentExtensions?: string[];
37
/** Enable automatic request retries (default: false) */
38
autoRetry?: boolean;
39
/** Maximum retry delay in milliseconds */
40
maxRetryDelay?: number;
41
/** Maximum number of retry attempts */
42
maxRetries?: number;
43
/** Validation client configuration */
44
validationClient?: ValidationClientOptions;
45
/** Request timeout in milliseconds */
46
timeout?: number;
47
/** Enable HTTP Keep-Alive */
48
keepAlive?: boolean;
49
/** Keep-Alive timeout in milliseconds */
50
keepAliveMsecs?: number;
51
/** Maximum number of sockets per host */
52
maxSockets?: number;
53
/** Maximum total number of sockets */
54
maxTotalSockets?: number;
55
/** Maximum number of free sockets */
56
maxFreeSockets?: number;
57
/** Socket scheduling algorithm */
58
scheduling?: "fifo" | "lifo" | undefined;
59
/** Certificate Authority for HTTPS requests */
60
ca?: string | Buffer;
61
}
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
import TwilioSDK from "twilio";
68
69
// Basic authentication with Account SID and Auth Token
70
const client = TwilioSDK("AC123...", "auth_token_here");
71
72
// API Key authentication
73
const client = TwilioSDK("SK456...", "api_secret_here", {
74
accountSid: "AC123..."
75
});
76
77
// Environment variable authentication
78
const client = TwilioSDK(); // Uses TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN
79
80
// Advanced configuration
81
const client = TwilioSDK("AC123...", "auth_token", {
82
region: "sydney",
83
edge: "au1",
84
autoRetry: true,
85
maxRetries: 3,
86
timeout: 30000,
87
logLevel: "debug"
88
});
89
```
90
91
### Core API Domain (api)
92
93
The main Twilio REST API v2010 domain containing core communication resources.
94
95
```typescript { .api }
96
/** Core Twilio REST API v2010 domain */
97
api: Api;
98
99
interface Api {
100
/** Account management and configuration */
101
account: AccountContext;
102
accounts: AccountListInstance;
103
104
// Legacy direct access (deprecated - use account.* instead)
105
addresses: AddressListInstance;
106
applications: ApplicationListInstance;
107
calls: CallListInstance;
108
conferences: ConferenceListInstance;
109
incomingPhoneNumbers: IncomingPhoneNumberListInstance;
110
keys: KeyListInstance;
111
messages: MessageListInstance;
112
notifications: NotificationListInstance;
113
outgoingCallerIds: OutgoingCallerIdListInstance;
114
queues: QueueListInstance;
115
recordings: RecordingListInstance;
116
shortCodes: ShortCodeListInstance;
117
signingKeys: SigningKeyListInstance;
118
tokens: TokenListInstance;
119
transcriptions: TranscriptionListInstance;
120
usage: UsageListInstance;
121
}
122
```
123
124
### Communication Service Domains
125
126
Service domains for various communication channels and capabilities.
127
128
```typescript { .api }
129
/** Messaging services and templates */
130
messaging: Messaging;
131
132
/** Voice services and applications */
133
voice: Voice;
134
135
/** Video communications and rooms */
136
video: Video;
137
138
/** Chat services (legacy - use conversations instead) */
139
chat: Chat;
140
141
/** Modern conversations API */
142
conversations: Conversations;
143
144
/** IP Messaging services (legacy) */
145
ipMessaging: IpMessaging;
146
```
147
148
### Platform and Infrastructure Services
149
150
Core platform services for application infrastructure and management.
151
152
```typescript { .api }
153
/** Real-time data synchronization */
154
sync: Sync;
155
156
/** Contact center and workforce management */
157
taskrouter: Taskrouter;
158
159
/** Visual workflow builder */
160
studio: Studio;
161
162
/** Serverless functions and assets */
163
serverless: Serverless;
164
165
/** Multi-channel notifications */
166
notify: Notify;
167
168
/** Phone number lookup and validation */
169
lookups: Lookups;
170
171
/** Usage and billing insights */
172
insights: Insights;
173
174
/** Call and message monitoring */
175
monitor: Monitor;
176
177
/** Pricing information for services */
178
pricing: Pricing;
179
```
180
181
### Security and Authentication Services
182
183
Services for authentication, verification, and security compliance.
184
185
```typescript { .api }
186
/** Two-factor authentication and verification */
187
verify: Verify;
188
189
/** Identity and access management */
190
iam: Iam;
191
192
/** OAuth authentication services */
193
oauth: Oauth;
194
195
/** Regulatory compliance and trust */
196
trusthub: Trusthub;
197
198
/** Preview IAM features */
199
previewIam: PreviewIam;
200
```
201
202
### Specialized Service Domains
203
204
Domain-specific services for specialized use cases.
205
206
```typescript { .api }
207
/** IoT connectivity with Super SIM */
208
supersim: Supersim;
209
210
/** Wireless connectivity management */
211
wireless: Wireless;
212
213
/** SIP trunking services */
214
trunking: Trunking;
215
216
/** Anonymous communications */
217
proxy: Proxy;
218
219
/** Phone number routing and management */
220
routes: Routes;
221
222
/** Phone number management */
223
numbers: Numbers;
224
225
/** Content management and templates */
226
content: Content;
227
228
/** Marketplace integrations */
229
marketplace: Marketplace;
230
231
/** Events and webhooks */
232
events: Events;
233
234
/** AI and machine learning services */
235
intelligence: Intelligence;
236
237
/** AI assistants and automation */
238
assistants: Assistants;
239
240
/** Contact center operations */
241
flexApi: FlexApi;
242
243
/** Customer engagement platform */
244
frontlineApi: FrontlineApi;
245
246
/** Data export services */
247
bulkexports: Bulkexports;
248
249
/** Account and sub-account management */
250
accounts: Accounts;
251
252
/** Preview and experimental features */
253
preview: Preview;
254
```
255
256
### Request Method
257
258
Low-level request method for direct API calls with full control over HTTP parameters.
259
260
```typescript { .api }
261
/**
262
* Makes a request to the Twilio API using the configured HTTP client
263
* @param opts - Request configuration options
264
* @returns Promise resolving to the API response
265
*/
266
request(opts: RequestOpts): Promise<any>;
267
268
interface RequestOpts {
269
/** HTTP method for the request */
270
method?: HttpMethod;
271
/** Full URI for the API endpoint */
272
uri?: string;
273
/** Username for authentication (overrides client default) */
274
username?: string;
275
/** Password for authentication (overrides client default) */
276
password?: string;
277
/** Custom authentication strategy */
278
authStrategy?: AuthStrategy;
279
/** HTTP headers for the request */
280
headers?: Headers;
281
/** Query parameters for GET requests */
282
params?: object;
283
/** Request body data for POST/PUT requests */
284
data?: object;
285
/** Request timeout in milliseconds */
286
timeout?: number;
287
/** Allow HTTP redirects */
288
allowRedirects?: boolean;
289
/** Log level for this specific request */
290
logLevel?: string;
291
}
292
293
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "PATCH";
294
295
interface Headers {
296
[key: string]: string;
297
}
298
```
299
300
**Usage Examples:**
301
302
```typescript
303
// Direct API call example
304
const response = await client.request({
305
method: "POST",
306
uri: "https://api.twilio.com/2010-04-01/Accounts/AC123.../Messages.json",
307
data: {
308
From: "+1234567890",
309
To: "+0987654321",
310
Body: "Hello from Twilio!"
311
}
312
});
313
314
// Custom headers and authentication
315
const response = await client.request({
316
method: "GET",
317
uri: "https://api.twilio.com/2010-04-01/Accounts/AC123.../Calls.json",
318
headers: {
319
"Accept": "application/json",
320
"Custom-Header": "value"
321
},
322
params: {
323
Status: "completed",
324
PageSize: 50
325
}
326
});
327
```
328
329
### SSL Certificate Validation
330
331
Utility method to test SSL certificate compatibility.
332
333
```typescript { .api }
334
/**
335
* Test SSL certificate compatibility by making a request to Twilio's test endpoint
336
* @throws RestException if the SSL test fails
337
* @returns Promise resolving to the test response
338
*/
339
validateSslCert(): Promise<any>;
340
```
341
342
### Common Resource Patterns
343
344
All Twilio resources follow consistent patterns for CRUD operations.
345
346
```typescript { .api }
347
// List resources (with pagination)
348
interface ListInstance<T> {
349
create(params: CreateParams): Promise<T>;
350
list(params?: ListParams): Promise<T[]>;
351
page(params?: PageParams): Promise<Page<T>>;
352
each(callback: (item: T) => void, done?: () => void): void;
353
each(params: EachParams, callback: (item: T) => void, done?: () => void): void;
354
}
355
356
// Individual resource context
357
interface Context<T> {
358
fetch(): Promise<T>;
359
update(params: UpdateParams): Promise<T>;
360
remove(): Promise<boolean>;
361
}
362
363
// Pagination support
364
interface Page<T> {
365
instances: T[];
366
nextPageUrl?: string;
367
previousPageUrl?: string;
368
meta: PageMeta;
369
}
370
371
interface PageMeta {
372
page: number;
373
pageSize: number;
374
firstPageUrl: string;
375
nextPageUrl?: string;
376
previousPageUrl?: string;
377
url: string;
378
key: string;
379
}
380
```
381
382
**Usage Examples:**
383
384
```typescript
385
// Creating resources
386
const message = await client.messages.create({
387
body: "Hello World",
388
from: "+1234567890",
389
to: "+0987654321"
390
});
391
392
const call = await client.calls.create({
393
url: "http://demo.twilio.com/docs/voice.xml",
394
from: "+1234567890",
395
to: "+0987654321"
396
});
397
398
// Fetching individual resources
399
const message = await client.messages("MM123...").fetch();
400
const call = await client.calls("CA456...").fetch();
401
402
// Updating resources
403
const updatedCall = await client.calls("CA456...").update({
404
status: "completed"
405
});
406
407
// Listing resources with pagination
408
const messages = await client.messages.list({
409
from: "+1234567890",
410
dateSentAfter: new Date("2023-01-01")
411
});
412
413
// Iterating through all resources
414
client.messages.each({
415
from: "+1234567890",
416
pageSize: 100
417
}, (message) => {
418
console.log(message.sid, message.body);
419
});
420
```
421
422
## Types
423
424
```typescript { .api }
425
interface ValidationClientOptions {
426
/** Enable request validation */
427
enabled?: boolean;
428
/** Validation timeout in milliseconds */
429
timeout?: number;
430
}
431
432
interface AuthStrategy {
433
/** Apply authentication to the request */
434
apply(request: RequestConfig): Promise<RequestConfig>;
435
}
436
437
interface RequestConfig {
438
method: HttpMethod;
439
url: string;
440
headers: Headers;
441
data?: any;
442
timeout?: number;
443
}
444
```