or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-services.mdauthentication-jwt.mdcore-communications.mdindex.mdinfrastructure.mdrest-client.mdtwiml-generation.mdwebhooks-validation.md

rest-client.mddocs/

0

# REST Client

1

2

The main Twilio client class providing access to all Twilio services and resources. Handles authentication, regional configuration, and provides both service-specific and direct resource access patterns.

3

4

## Capabilities

5

6

### Client Initialization

7

8

The primary entry point for accessing all Twilio APIs. Supports multiple authentication methods, regional configuration, and custom HTTP clients.

9

10

```python { .api }

11

class Client:

12

def __init__(

13

self,

14

username: str = None,

15

password: str = None,

16

account_sid: str = None,

17

region: str = None,

18

http_client: HttpClient = None,

19

environment: dict = None,

20

edge: str = None,

21

user_agent_extensions: list = None,

22

credential_provider: CredentialProvider = None

23

):

24

"""

25

Initialize the Twilio client.

26

27

Args:

28

username (str): Account SID or API Key SID

29

password (str): Auth Token or API Key Secret

30

account_sid (str): Account SID (when using API Key)

31

region (str): Twilio region (default: 'us1')

32

http_client (HttpClient): Custom HTTP client

33

environment (dict): Environment variables

34

edge (str): Twilio edge location

35

user_agent_extensions (list): Additional user agent strings

36

credential_provider (CredentialProvider): Alternative auth method

37

"""

38

```

39

40

Basic initialization:

41

42

```python

43

from twilio.rest import Client

44

45

# Using Account SID and Auth Token

46

client = Client('ACxxxxx', 'your_auth_token')

47

48

# Using environment variables (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

49

client = Client()

50

51

# Using API Key

52

client = Client('SKxxxxx', 'api_secret', account_sid='ACxxxxx')

53

```

54

55

Regional configuration:

56

57

```python

58

# Specify Twilio region

59

client = Client('ACxxxxx', 'token', region='sydney')

60

61

# Specify edge location

62

client = Client('ACxxxxx', 'token', edge='dublin')

63

```

64

65

### Service Domain Access

66

67

Access to all Twilio service domains through client properties. Each service provides version-specific APIs and resource management.

68

69

```python { .api }

70

# Core API services

71

api: ApiV2010 # Core Twilio API (SMS, voice, etc.)

72

messaging: MessagingV1 # Messaging services and campaigns

73

chat: ChatV1 # Legacy chat service

74

conversations: ConversationsV1 # Enhanced messaging conversations

75

voice: VoiceV1 # Programmable Voice API

76

video: VideoV1 # Video conferencing

77

78

# Communication services

79

verify: VerifyV2 # Identity verification

80

notify: NotifyV1 # Push notifications

81

sync: SyncV1 # Real-time data sync

82

83

# Business services

84

taskrouter: TaskrouterV1 # Contact center routing

85

flex_api: Flex_ApiV1 # Contact center platform

86

frontline_api: Frontline_ApiV1 # Customer conversations

87

proxy: ProxyV1 # Anonymous communication

88

89

# Developer services

90

studio: StudioV1 # Visual workflow builder

91

serverless: ServerlessV1 # Functions and assets

92

events: EventsV1 # Event streaming

93

94

# Infrastructure services

95

numbers: NumbersV2 # Phone number management

96

pricing: PricingV2 # Service pricing

97

lookups: LookupsV2 # Phone number lookup

98

wireless: WirelessV1 # IoT connectivity

99

supersim: SupersimV1 # Global SIM management

100

trunking: TrunkingV1 # SIP trunking

101

102

# Analytics and monitoring

103

insights: InsightsV1 # Call quality analytics

104

intelligence: IntelligenceV2 # Call transcription

105

monitor: MonitorV1 # Usage monitoring

106

107

# Marketplace and compliance

108

marketplace: MarketplaceV1 # Add-on marketplace

109

trusthub: TrusthubV1 # Regulatory compliance

110

bulkexports: BulkexportsV1 # Data export

111

112

# Specialized services

113

content: ContentV2 # Rich messaging content

114

routes: RoutesV2 # Phone number routing

115

assistants: AssistantsV1 # AI assistants

116

iam: IamV1 # Identity management

117

oauth: OauthV1 # OAuth provider

118

119

# Preview and Beta services

120

preview: PreviewV1 # Preview API features

121

frontline_api: Frontline_ApiV1 # Customer conversation management

122

preview_iam: Preview_IamV1 # Preview identity management

123

ip_messaging: Ip_MessagingV2 # Legacy IP messaging (deprecated)

124

125

# Additional services

126

accounts: AccountsV1 # Account management and configuration

127

```

128

129

Usage examples:

130

131

```python

132

# Access messaging service

133

messaging_service = client.messaging.v1.services.create(

134

friendly_name="My Service"

135

)

136

137

# Access video room

138

room = client.video.v1.rooms.create(

139

unique_name="my-room",

140

type="group"

141

)

142

143

# Access verification service

144

verification = client.verify.v2.services.get("VAxxxxx").verifications.create(

145

to="+15551234567",

146

channel="sms"

147

)

148

```

149

150

### Direct Resource Access

151

152

Convenient shortcuts to commonly used resources without navigating the service hierarchy.

153

154

```python { .api }

155

# Messaging resources

156

messages: MessageList # SMS/MMS messages

157

applications: ApplicationList # TwiML applications

158

159

# Voice resources

160

calls: CallList # Voice calls

161

conferences: ConferenceList # Conference calls

162

recordings: RecordingList # Call recordings

163

queues: QueueList # Call queues

164

165

# Account resources

166

addresses: AddressList # Address validation

167

keys: KeyList # API keys

168

tokens: TokenList # Access tokens

169

170

# Phone number resources

171

available_phone_numbers: AvailablePhoneNumberCountryList

172

incoming_phone_numbers: IncomingPhoneNumberList

173

outgoing_caller_ids: OutgoingCallerIdList

174

short_codes: ShortCodeList

175

176

# SIP resources

177

sip: SipList # SIP domains and credentials

178

179

# Usage and monitoring

180

usage: UsageList # Usage statistics and records

181

```

182

183

Direct access examples:

184

185

```python

186

# Send SMS directly

187

message = client.messages.create(

188

body="Hello World",

189

from_="+15551234567",

190

to="+15559876543"

191

)

192

193

# Make call directly

194

call = client.calls.create(

195

url="http://demo.twilio.com/docs/voice.xml",

196

from_="+15551234567",

197

to="+15559876543"

198

)

199

200

# List recordings

201

for recording in client.recordings.list(limit=20):

202

print(recording.sid, recording.duration)

203

204

# Get available phone numbers

205

numbers = client.available_phone_numbers("US").local.list(

206

area_code="415",

207

limit=10

208

)

209

```

210

211

### Account Management

212

213

Access account information and manage subaccounts through the main client.

214

215

```python { .api }

216

# Account properties

217

account_sid: str # Current account SID

218

auth_token: str # Current auth token (masked)

219

220

# Account methods

221

def account(self) -> AccountContext:

222

"""Access current account details and settings"""

223

224

def accounts(self, sid: str = None) -> AccountList:

225

"""Access account list for subaccount management"""

226

```

227

228

Account usage:

229

230

```python

231

# Get current account details

232

account = client.account.fetch()

233

print(f"Account: {account.friendly_name}")

234

print(f"Status: {account.status}")

235

236

# Create subaccount

237

subaccount = client.accounts.create(

238

friendly_name="Development Account"

239

)

240

241

# Switch to subaccount

242

sub_client = Client(subaccount.sid, subaccount.auth_token)

243

```

244

245

### Error Handling

246

247

The client automatically handles HTTP errors and converts them to appropriate Python exceptions.

248

249

```python { .api }

250

# Base exceptions

251

TwilioException # Base exception class

252

TwilioRestException # REST API errors

253

254

# HTTP-specific exceptions

255

TwilioHttpException # HTTP transport errors

256

```

257

258

Error handling example:

259

260

```python

261

from twilio.base.exceptions import TwilioRestException

262

263

try:

264

message = client.messages.create(

265

body="Test message",

266

from_="+15551234567",

267

to="invalid_number"

268

)

269

except TwilioRestException as e:

270

print(f"Twilio error {e.code}: {e.message}")

271

print(f"Status: {e.status}")

272

print(f"More info: {e.more_info}")

273

except Exception as e:

274

print(f"Other error: {str(e)}")

275

```

276

277

## Configuration Options

278

279

### Environment Variables

280

281

The client automatically reads configuration from environment variables:

282

283

```python

284

# Environment variable names

285

TWILIO_ACCOUNT_SID # Account SID

286

TWILIO_AUTH_TOKEN # Auth Token

287

TWILIO_API_KEY # API Key SID

288

TWILIO_API_SECRET # API Key Secret

289

TWILIO_REGION # Default region

290

TWILIO_EDGE # Default edge

291

```

292

293

### Regional Configuration

294

295

Configure the client for specific Twilio regions and edge locations:

296

297

```python

298

# Available regions

299

'us1' # United States (default)

300

'ie1' # Ireland

301

'au1' # Australia

302

'sg1' # Singapore

303

'jp1' # Japan

304

305

# Available edges

306

'sydney' # Australia

307

'dublin' # Ireland

308

'tokyo' # Japan

309

'singapore' # Singapore

310

```

311

312

### Custom HTTP Client

313

314

Provide a custom HTTP client for advanced configuration:

315

316

```python

317

from twilio.http.http_client import TwilioHttpClient

318

319

# Custom HTTP client with connection pooling

320

http_client = TwilioHttpClient(

321

pool_connections=20,

322

pool_maxsize=20,

323

max_retries=3

324

)

325

326

client = Client(http_client=http_client)

327

```