CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-twilio

Twilio API client and TwiML generator for comprehensive telecommunications services

Overview
Eval results
Files

rest-client.mddocs/

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.

Capabilities

Client Initialization

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

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
    ):
        """
        Initialize the Twilio client.
        
        Args:
            username (str): Account SID or API Key SID
            password (str): Auth Token or API Key Secret
            account_sid (str): Account SID (when using API Key)
            region (str): Twilio region (default: 'us1')
            http_client (HttpClient): Custom HTTP client
            environment (dict): Environment variables
            edge (str): Twilio edge location
            user_agent_extensions (list): Additional user agent strings
            credential_provider (CredentialProvider): Alternative auth method
        """

Basic initialization:

from twilio.rest import Client

# Using Account SID and Auth Token
client = Client('ACxxxxx', 'your_auth_token')

# Using environment variables (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
client = Client()

# Using API Key
client = Client('SKxxxxx', 'api_secret', account_sid='ACxxxxx')

Regional configuration:

# Specify Twilio region
client = Client('ACxxxxx', 'token', region='sydney')

# Specify edge location
client = Client('ACxxxxx', 'token', edge='dublin')

Service Domain Access

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

# Core API services
api: ApiV2010                    # Core Twilio API (SMS, voice, etc.)
messaging: MessagingV1           # Messaging services and campaigns
chat: ChatV1                     # Legacy chat service  
conversations: ConversationsV1   # Enhanced messaging conversations
voice: VoiceV1                   # Programmable Voice API
video: VideoV1                   # Video conferencing

# Communication services
verify: VerifyV2                 # Identity verification
notify: NotifyV1                 # Push notifications
sync: SyncV1                     # Real-time data sync

# Business services  
taskrouter: TaskrouterV1         # Contact center routing
flex_api: Flex_ApiV1             # Contact center platform
frontline_api: Frontline_ApiV1   # Customer conversations
proxy: ProxyV1                   # Anonymous communication

# Developer services
studio: StudioV1                 # Visual workflow builder
serverless: ServerlessV1         # Functions and assets
events: EventsV1                 # Event streaming

# Infrastructure services
numbers: NumbersV2               # Phone number management
pricing: PricingV2               # Service pricing
lookups: LookupsV2              # Phone number lookup
wireless: WirelessV1            # IoT connectivity
supersim: SupersimV1            # Global SIM management
trunking: TrunkingV1            # SIP trunking

# Analytics and monitoring
insights: InsightsV1            # Call quality analytics
intelligence: IntelligenceV2    # Call transcription
monitor: MonitorV1              # Usage monitoring

# Marketplace and compliance
marketplace: MarketplaceV1      # Add-on marketplace
trusthub: TrusthubV1           # Regulatory compliance
bulkexports: BulkexportsV1     # Data export

# Specialized services
content: ContentV2              # Rich messaging content
routes: RoutesV2               # Phone number routing
assistants: AssistantsV1       # AI assistants
iam: IamV1                     # Identity management
oauth: OauthV1                 # OAuth provider

# Preview and Beta services
preview: PreviewV1             # Preview API features
frontline_api: Frontline_ApiV1 # Customer conversation management
preview_iam: Preview_IamV1     # Preview identity management
ip_messaging: Ip_MessagingV2   # Legacy IP messaging (deprecated)

# Additional services
accounts: AccountsV1           # Account management and configuration

Usage examples:

# Access messaging service
messaging_service = client.messaging.v1.services.create(
    friendly_name="My Service"
)

# Access video room
room = client.video.v1.rooms.create(
    unique_name="my-room",
    type="group"
)

# Access verification service
verification = client.verify.v2.services.get("VAxxxxx").verifications.create(
    to="+15551234567",
    channel="sms"
)

Direct Resource Access

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

# Messaging resources
messages: MessageList              # SMS/MMS messages
applications: ApplicationList      # TwiML applications

# Voice resources  
calls: CallList                   # Voice calls
conferences: ConferenceList       # Conference calls
recordings: RecordingList         # Call recordings
queues: QueueList                # Call queues

# Account resources
addresses: AddressList            # Address validation
keys: KeyList                    # API keys
tokens: TokenList                # Access tokens

# Phone number resources
available_phone_numbers: AvailablePhoneNumberCountryList
incoming_phone_numbers: IncomingPhoneNumberList
outgoing_caller_ids: OutgoingCallerIdList
short_codes: ShortCodeList

# SIP resources
sip: SipList                     # SIP domains and credentials

# Usage and monitoring
usage: UsageList                 # Usage statistics and records

Direct access examples:

# Send SMS directly
message = client.messages.create(
    body="Hello World",
    from_="+15551234567", 
    to="+15559876543"
)

# Make call directly
call = client.calls.create(
    url="http://demo.twilio.com/docs/voice.xml",
    from_="+15551234567",
    to="+15559876543"
)

# List recordings
for recording in client.recordings.list(limit=20):
    print(recording.sid, recording.duration)

# Get available phone numbers
numbers = client.available_phone_numbers("US").local.list(
    area_code="415",
    limit=10
)

Account Management

Access account information and manage subaccounts through the main client.

# Account properties
account_sid: str                 # Current account SID
auth_token: str                 # Current auth token (masked)

# Account methods
def account(self) -> AccountContext:
    """Access current account details and settings"""

def accounts(self, sid: str = None) -> AccountList:
    """Access account list for subaccount management"""

Account usage:

# Get current account details
account = client.account.fetch()
print(f"Account: {account.friendly_name}")
print(f"Status: {account.status}")

# Create subaccount
subaccount = client.accounts.create(
    friendly_name="Development Account"
)

# Switch to subaccount
sub_client = Client(subaccount.sid, subaccount.auth_token)

Error Handling

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

# Base exceptions
TwilioException                  # Base exception class
TwilioRestException             # REST API errors

# HTTP-specific exceptions  
TwilioHttpException             # HTTP transport errors

Error handling example:

from twilio.base.exceptions import TwilioRestException

try:
    message = client.messages.create(
        body="Test message",
        from_="+15551234567",
        to="invalid_number"
    )
except TwilioRestException as e:
    print(f"Twilio error {e.code}: {e.message}")
    print(f"Status: {e.status}")
    print(f"More info: {e.more_info}")
except Exception as e:
    print(f"Other error: {str(e)}")

Configuration Options

Environment Variables

The client automatically reads configuration from environment variables:

# Environment variable names
TWILIO_ACCOUNT_SID              # Account SID
TWILIO_AUTH_TOKEN              # Auth Token  
TWILIO_API_KEY                 # API Key SID
TWILIO_API_SECRET              # API Key Secret
TWILIO_REGION                  # Default region
TWILIO_EDGE                    # Default edge

Regional Configuration

Configure the client for specific Twilio regions and edge locations:

# Available regions
'us1'      # United States (default)
'ie1'      # Ireland  
'au1'      # Australia
'sg1'      # Singapore
'jp1'      # Japan

# Available edges  
'sydney'   # Australia
'dublin'   # Ireland
'tokyo'    # Japan
'singapore' # Singapore

Custom HTTP Client

Provide a custom HTTP client for advanced configuration:

from twilio.http.http_client import TwilioHttpClient

# Custom HTTP client with connection pooling
http_client = TwilioHttpClient(
    pool_connections=20,
    pool_maxsize=20,
    max_retries=3
)

client = Client(http_client=http_client)

Install with Tessl CLI

npx tessl i tessl/pypi-twilio

docs

advanced-services.md

authentication-jwt.md

core-communications.md

index.md

infrastructure.md

rest-client.md

twiml-generation.md

webhooks-validation.md

tile.json