or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-twilio

Twilio API client and TwiML generator for comprehensive telecommunications services

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/twilio@9.8.x

To install, run

npx @tessl/cli install tessl/pypi-twilio@9.8.0

0

# Twilio Python SDK

1

2

A comprehensive Python client library for the Twilio communications platform, enabling developers to programmatically send SMS messages, make voice calls, manage phone numbers, and handle various telecommunications services through Twilio's APIs. It offers both synchronous and asynchronous HTTP clients for API requests, supports TwiML generation for call flow control, provides OAuth 2.0 authentication capabilities, and includes extensive error handling with custom exception classes.

3

4

## Package Information

5

6

- **Package Name**: twilio

7

- **Language**: Python

8

- **Installation**: `pip install twilio`

9

10

## Core Imports

11

12

```python

13

from twilio.rest import Client

14

```

15

16

Common for TwiML generation:

17

18

```python

19

from twilio.twiml.voice_response import VoiceResponse

20

from twilio.twiml.messaging_response import MessagingResponse

21

```

22

23

Authentication and JWT:

24

25

```python

26

from twilio.jwt.access_token import AccessToken

27

from twilio.jwt.access_token.grants import VideoGrant, ChatGrant

28

```

29

30

Request validation:

31

32

```python

33

from twilio.request_validator import RequestValidator

34

```

35

36

## Basic Usage

37

38

```python

39

from twilio.rest import Client

40

41

# Initialize the client

42

client = Client('account_sid', 'auth_token')

43

44

# Send an SMS message

45

message = client.messages.create(

46

body="Hello from Python!",

47

from_='+1234567890',

48

to='+0987654321'

49

)

50

print(message.sid)

51

52

# Make a voice call

53

call = client.calls.create(

54

twiml='<Response><Say>Hello World</Say></Response>',

55

from_='+1234567890',

56

to='+0987654321'

57

)

58

print(call.sid)

59

60

# Generate TwiML for voice response

61

from twilio.twiml.voice_response import VoiceResponse

62

63

response = VoiceResponse()

64

response.say('Hello from Twilio!')

65

response.dial('+1234567890')

66

print(response) # Outputs XML

67

```

68

69

## Architecture

70

71

The Twilio Python SDK follows a hierarchical resource structure:

72

73

- **Client**: Main entry point providing access to all Twilio services

74

- **Services**: Domain-specific APIs (messaging, voice, video, etc.)

75

- **Resources**: API endpoints organized as lists and instances

76

- **TwiML**: XML generation classes for call/message flow control

77

- **JWT**: Token-based authentication for client-side applications

78

- **Infrastructure**: HTTP clients, authentication strategies, and utilities

79

80

This design provides both high-level convenience methods and low-level resource access, supporting everything from simple SMS sending to complex multi-party video conferences and automated call flows.

81

82

## Capabilities

83

84

### REST Client

85

86

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.

87

88

```python { .api }

89

class Client:

90

def __init__(

91

self,

92

username: str = None,

93

password: str = None,

94

account_sid: str = None,

95

region: str = None,

96

http_client: HttpClient = None,

97

environment: dict = None,

98

edge: str = None,

99

user_agent_extensions: list = None,

100

credential_provider: CredentialProvider = None

101

): ...

102

103

# Service domain properties

104

api: ApiV2010

105

messaging: MessagingV1

106

chat: ChatV1

107

video: VideoV1

108

voice: VoiceV1

109

verify: VerifyV2

110

# ... 25+ more services

111

112

# Direct resource shortcuts

113

messages: MessageList

114

calls: CallList

115

# ... many more

116

```

117

118

[REST Client](./rest-client.md)

119

120

### Core Communications

121

122

Fundamental telecommunications capabilities including SMS/MMS messaging, voice calls, phone number management, and basic account operations. These APIs form the core of Twilio's communication platform.

123

124

```python { .api }

125

# Message sending

126

def create(

127

to: str,

128

from_: str = None,

129

body: str = None,

130

media_url: list = None,

131

**kwargs

132

) -> MessageInstance: ...

133

134

# Voice calls

135

def create(

136

to: str,

137

from_: str = None,

138

twiml: str = None,

139

url: str = None,

140

**kwargs

141

) -> CallInstance: ...

142

```

143

144

[Core Communications](./core-communications.md)

145

146

### TwiML Generation

147

148

XML markup language generation for controlling voice calls and messaging flows. Provides Python classes that generate TwiML XML for call routing, text-to-speech, user input collection, and message handling.

149

150

```python { .api }

151

class VoiceResponse:

152

def say(self, message: str, **kwargs) -> Say: ...

153

def dial(self, number: str = None, **kwargs) -> Dial: ...

154

def gather(self, **kwargs) -> Gather: ...

155

def record(self, **kwargs) -> Record: ...

156

def hangup(self) -> Hangup: ...

157

def to_xml(self) -> str: ...

158

159

class MessagingResponse:

160

def message(self, body: str = None, **kwargs) -> Message: ...

161

def redirect(self, url: str, **kwargs) -> Redirect: ...

162

def to_xml(self) -> str: ...

163

164

class FaxResponse:

165

def receive(self, **kwargs) -> Receive: ...

166

def reject(self, reason: str = None) -> Reject: ...

167

def to_xml(self) -> str: ...

168

```

169

170

[TwiML Generation](./twiml-generation.md)

171

172

### Authentication & JWT

173

174

Token-based authentication system for client-side applications and access control. Includes access tokens, capability tokens, and various grant types for different Twilio services.

175

176

```python { .api }

177

class AccessToken:

178

def __init__(

179

self,

180

account_sid: str,

181

signing_key_sid: str,

182

secret: str,

183

ttl: int = 3600,

184

identity: str = None,

185

nbf: int = None

186

): ...

187

188

def add_grant(self, grant: AccessTokenGrant) -> AccessToken: ...

189

def to_jwt(self) -> str: ...

190

191

# Grant types

192

class VideoGrant(AccessTokenGrant): ...

193

class ChatGrant(AccessTokenGrant): ...

194

class VoiceGrant(AccessTokenGrant): ...

195

class SyncGrant(AccessTokenGrant): ...

196

```

197

198

[Authentication & JWT](./authentication-jwt.md)

199

200

### Advanced Services

201

202

Specialized Twilio services including video conferencing, real-time chat, identity verification, push notifications, visual workflows, serverless functions, and contact center solutions.

203

204

```python { .api }

205

# Video service

206

video.rooms.create(

207

unique_name: str = None,

208

type: str = None,

209

**kwargs

210

) -> RoomInstance

211

212

# Chat/Conversations

213

conversations.conversations.create(

214

friendly_name: str = None,

215

**kwargs

216

) -> ConversationInstance

217

218

# Verify service

219

verify.services.create(

220

friendly_name: str,

221

**kwargs

222

) -> ServiceInstance

223

```

224

225

[Advanced Services](./advanced-services.md)

226

227

### Webhooks & Validation

228

229

Request signature validation for securing webhook endpoints and ensuring requests originate from Twilio. Provides utilities for computing and validating request signatures.

230

231

```python { .api }

232

class RequestValidator:

233

def __init__(self, auth_token: str): ...

234

235

def validate(

236

self,

237

uri: str,

238

params: dict,

239

signature: str

240

) -> bool: ...

241

242

def compute_signature(

243

self,

244

uri: str,

245

params: dict

246

) -> str: ...

247

```

248

249

[Webhooks & Validation](./webhooks-validation.md)

250

251

### Infrastructure

252

253

Low-level infrastructure including HTTP clients, authentication strategies, credential providers, base classes, and exception handling. These components support the high-level APIs and can be customized for advanced use cases.

254

255

```python { .api }

256

class TwilioHttpClient(HttpClient):

257

def request(

258

self,

259

method: str,

260

uri: str,

261

data: dict = None,

262

headers: dict = None,

263

**kwargs

264

) -> Response: ...

265

266

class TwilioException(Exception): ...

267

class TwilioRestException(TwilioException): ...

268

```

269

270

[Infrastructure](./infrastructure.md)

271

272

## Error Handling

273

274

The SDK provides comprehensive error handling with specific exception types:

275

276

```python { .api }

277

class TwilioException(Exception):

278

"""Base exception for all Twilio errors"""

279

280

class TwilioRestException(TwilioException):

281

"""REST API errors with detailed information"""

282

status: int

283

uri: str

284

code: int

285

message: str

286

details: dict

287

more_info: str

288

```

289

290

Common error handling pattern:

291

292

```python

293

from twilio.base.exceptions import TwilioRestException

294

295

try:

296

message = client.messages.create(

297

body="Hello World",

298

from_='+1234567890',

299

to='+invalid'

300

)

301

except TwilioRestException as e:

302

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

303

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

304

```