or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

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

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

index.mddocs/

Twilio Python SDK

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.

Package Information

  • Package Name: twilio
  • Language: Python
  • Installation: pip install twilio

Core Imports

from twilio.rest import Client

Common for TwiML generation:

from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse

Authentication and JWT:

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

Request validation:

from twilio.request_validator import RequestValidator

Basic Usage

from 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 XML

Architecture

The Twilio Python SDK follows a hierarchical resource structure:

  • Client: Main entry point providing access to all Twilio services
  • Services: Domain-specific APIs (messaging, voice, video, etc.)
  • Resources: API endpoints organized as lists and instances
  • TwiML: XML generation classes for call/message flow control
  • JWT: Token-based authentication for client-side applications
  • Infrastructure: HTTP clients, authentication strategies, and utilities

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.

Capabilities

REST Client

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 more

REST Client

Core Communications

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.

# 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: ...

Core Communications

TwiML Generation

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: ...

TwiML Generation

Authentication & JWT

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): ...

Authentication & JWT

Advanced Services

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
) -> ServiceInstance

Advanced Services

Webhooks & Validation

Request 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: ...

Webhooks & Validation

Infrastructure

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): ...

Infrastructure

Error Handling

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: str

Common 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}")