Twilio API client and TwiML generator for comprehensive telecommunications services
npx @tessl/cli install tessl/pypi-twilio@9.8.0A 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.
pip install twiliofrom twilio.rest import ClientCommon for TwiML generation:
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponseAuthentication and JWT:
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import VideoGrant, ChatGrantRequest validation:
from twilio.request_validator import RequestValidatorfrom twilio.rest import Client
# Initialize the client
client = Client('account_sid', 'auth_token')
# Send an SMS message
message = client.messages.create(
body="Hello from Python!",
from_='+1234567890',
to='+0987654321'
)
print(message.sid)
# Make a voice call
call = client.calls.create(
twiml='<Response><Say>Hello World</Say></Response>',
from_='+1234567890',
to='+0987654321'
)
print(call.sid)
# Generate TwiML for voice response
from twilio.twiml.voice_response import VoiceResponse
response = VoiceResponse()
response.say('Hello from Twilio!')
response.dial('+1234567890')
print(response) # Outputs XMLThe Twilio Python SDK follows a hierarchical resource structure:
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.
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.
class Client:
def __init__(
self,
username: str = None,
password: str = None,
account_sid: str = None,
region: str = None,
http_client: HttpClient = None,
environment: dict = None,
edge: str = None,
user_agent_extensions: list = None,
credential_provider: CredentialProvider = None
): ...
# Service domain properties
api: ApiV2010
messaging: MessagingV1
chat: ChatV1
video: VideoV1
voice: VoiceV1
verify: VerifyV2
# ... 25+ more services
# Direct resource shortcuts
messages: MessageList
calls: CallList
# ... many moreFundamental 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.
# Message sending
def create(
to: str,
from_: str = None,
body: str = None,
media_url: list = None,
**kwargs
) -> MessageInstance: ...
# Voice calls
def create(
to: str,
from_: str = None,
twiml: str = None,
url: str = None,
**kwargs
) -> CallInstance: ...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.
class VoiceResponse:
def say(self, message: str, **kwargs) -> Say: ...
def dial(self, number: str = None, **kwargs) -> Dial: ...
def gather(self, **kwargs) -> Gather: ...
def record(self, **kwargs) -> Record: ...
def hangup(self) -> Hangup: ...
def to_xml(self) -> str: ...
class MessagingResponse:
def message(self, body: str = None, **kwargs) -> Message: ...
def redirect(self, url: str, **kwargs) -> Redirect: ...
def to_xml(self) -> str: ...
class FaxResponse:
def receive(self, **kwargs) -> Receive: ...
def reject(self, reason: str = None) -> Reject: ...
def to_xml(self) -> str: ...Token-based authentication system for client-side applications and access control. Includes access tokens, capability tokens, and various grant types for different Twilio services.
class AccessToken:
def __init__(
self,
account_sid: str,
signing_key_sid: str,
secret: str,
ttl: int = 3600,
identity: str = None,
nbf: int = None
): ...
def add_grant(self, grant: AccessTokenGrant) -> AccessToken: ...
def to_jwt(self) -> str: ...
# Grant types
class VideoGrant(AccessTokenGrant): ...
class ChatGrant(AccessTokenGrant): ...
class VoiceGrant(AccessTokenGrant): ...
class SyncGrant(AccessTokenGrant): ...Specialized Twilio services including video conferencing, real-time chat, identity verification, push notifications, visual workflows, serverless functions, and contact center solutions.
# Video service
video.rooms.create(
unique_name: str = None,
type: str = None,
**kwargs
) -> RoomInstance
# Chat/Conversations
conversations.conversations.create(
friendly_name: str = None,
**kwargs
) -> ConversationInstance
# Verify service
verify.services.create(
friendly_name: str,
**kwargs
) -> ServiceInstanceRequest signature validation for securing webhook endpoints and ensuring requests originate from Twilio. Provides utilities for computing and validating request signatures.
class RequestValidator:
def __init__(self, auth_token: str): ...
def validate(
self,
uri: str,
params: dict,
signature: str
) -> bool: ...
def compute_signature(
self,
uri: str,
params: dict
) -> str: ...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.
class TwilioHttpClient(HttpClient):
def request(
self,
method: str,
uri: str,
data: dict = None,
headers: dict = None,
**kwargs
) -> Response: ...
class TwilioException(Exception): ...
class TwilioRestException(TwilioException): ...The SDK provides comprehensive error handling with specific exception types:
class TwilioException(Exception):
"""Base exception for all Twilio errors"""
class TwilioRestException(TwilioException):
"""REST API errors with detailed information"""
status: int
uri: str
code: int
message: str
details: dict
more_info: strCommon error handling pattern:
from twilio.base.exceptions import TwilioRestException
try:
message = client.messages.create(
body="Hello World",
from_='+1234567890',
to='+invalid'
)
except TwilioRestException as e:
print(f"Error {e.code}: {e.message}")
print(f"More info: {e.more_info}")