twilio-python

repository·main·Indexed 24 days ago

https://github.com/twilio/twilio-python

The official Python helper library for the Twilio API. It allows developers to interact with Twilio services such as SMS and Voice using idiomatic Python code. The library supports Python 3.7 through 3.13 and provides features including asynchronous API requests via AsyncTwilioHttpClient, automatic paging for record collections, TwiML response generation, and support for custom HTTP clients for proxy authentication or mocking.

Tokens
4.9K
Snippets
17
Records
23
Agent score
85%

What's inside twilio-python

  1. How the HttpClient abstraction works

    main

    The twilio.http.HttpClient is an abstraction that allows you to plug in any implementation for making HTTP requests.

    • twilio.http.HttpClient: The base abstraction/interface.
    • twilio.http.TwilioHttpClient: The standard implementation provided by the library that wraps the underlying HTTP logic.

    To create a custom client, you should inherit from TwilioHttpClient and override the request method.

  2. Check supported versions of twilio-python

    main
    Twilio only provides support for the current MAJOR version of the twilio-python library. New features, bug fixes, and security updates are exclusively applied to the current major version. If you are using an older major version, you will not receive updates.
  3. Use cases for custom HTTP clients

    main

    Injecting a custom http_client into the Twilio API request pipeline allows for several advanced patterns:

    1. Proxy Authentication: Connecting to and authenticating with enterprise proxy servers.
    2. Custom Headers/Auth: Adding specific HTTP headers or authorization schemes required by upstream infrastructure.
    3. Mocking for Testing: Implementing a client that returns mocked responses to allow unit and integration tests to run without making real network calls to Twilio.
  4. Understand the twilio-python versioning strategy

    main

    The twilio-python library follows a modified Semantic Versioning (MAJOR.MINOR.PATCH) pattern. To ensure stability and avoid breaking changes in your application, it is strongly recommended to pin at least the major version (and ideally the minor version) in your dependency management.

    • PATCH (MAJOR.MINOR.PATCH): Incremented for backwards-compatible bug fixes. These are generally safe to upgrade.
    • MINOR (MAJOR.MINOR.PATCH): Incremented for new backwards-compatible features or small breaking changes (such as limited function signature changes). Upgrading may require manual code adjustments.
    • MAJOR (MAJOR.MINOR.PATCH): Incremented for significant breaking changes that require extensive code reworking. New major versions are communicated in advance via Release Candidates.
  5. Iterate through records with paging

    main

    The library handles API paging automatically for collections like calls and messages. You can use list() to eagerly fetch all records or stream() to lazily iterate through them.

    Paging Parameters

    • limit: The maximum number of total records you want to fetch.
    • page_size: The number of records to retrieve in each individual API request (page).

    Behavior Examples:

    • list(limit=20, page_size=20): 1 API call fetching 20 records.
    • list(limit=20, page_size=10): 2 API calls fetching 10 records each.
    • list(limit=20, page_size=100): 1 API call fetching 100 records, but the method returns only the first 20.
    from twilio.rest import Client
    
    account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    auth_token = "your_auth_token"
    client = Client(account_sid, auth_token)
    
    # Iterate through all messages
    for sms in client.messages.list():
      print(sms.to)
    
    # Use limit and page_size
    client.messages.list(limit=20, page_size=10)
  6. Install the twilio-python library

    main

    Install the Twilio Python helper library from PyPI using pip.

    If you encounter permission errors, you may need to use sudo. On Windows, if the installation fails, ensure that directory paths are not exceeding 260 characters by enabling Long Paths.

    pip3 install twilio
  7. Use a custom HTTP client with the Twilio Client

    main

    By default, the twilio.rest.Client constructor creates a default http_client. You can override this behavior by passing your own implementation of twilio.http.HttpClient to the http_client parameter. This is useful for connecting through enterprise proxy servers, adding custom headers, or mocking API responses for testing.

    import os
    from twilio.rest import Client
    from custom_client import MyRequestClass
    
    # Initialize your custom HTTP client
    my_request_client = MyRequestClass()
    
    # Pass it to the Client constructor
    client = Client(os.getenv("ACCOUNT_SID"), os.getenv("AUTH_TOKEN"),
                    http_client=my_request_client)
    
    # Use the client as normal
    message = client.messages.create(
        to="+15558675310",
        body="Hey there!",
        from="+15017122661"
    )
  8. Upgrade from 7.x.x to 8.x.x

    main

    Upgrading to version 8.x.x involves several breaking changes regarding supported Python versions, TwiML methods, and TaskRouter API paths.

    Python Version Requirements

    • Dropped support for Python 3.6.
    • Python 3.7 is the new minimum required version.

    TwiML Voice Method Changes

    Several deprecated TwiML Voice methods have been renamed to remove the ssml_ prefix:

    • Refer.refer_sip() $\rightarrow$ Refer.sip()
    • Say.ssml_break() $\rightarrow$ Say.break_()
    • Say.ssml_emphasis() $\rightarrow$ Say.emphasis()
    • Say.ssml_lang() $\rightarrow$ Say.lang()
    • Say.ssml_p() $\rightarrow$ Say.p()
    • Say.ssml_phoneme() $\rightarrow$ Say.phoneme()
    • Say.ssml_prosody() $\rightarrow$ Say.prosody()
    • Say.ssml_s() $\rightarrow$ Say.s()
    • Say.ssml_say_as() $\rightarrow$ Say.say_as()
    • Say.ssml_sub() $\rightarrow$ Say.sub()
    • Say.ssml_w() $\rightarrow$ Say.w()

    JWT and Grant Changes

    • ConversationsGrant is deprecated; use VoiceGrant instead.
    • IpMessagingGrant has been removed.

    API Renames and TaskRouter Updates

    • twilio.rest.api.v2010.account.available_phone_number is now twilio.rest.api.v2010.account.available_phone_number_country.
    • TaskRouter Workers Statistics: Cumulative and Real-Time statistics no longer accept a WorkerSid in the path. They are now accessed via the .workers collection rather than a specific worker instance.

    Old TaskRouter Pattern:

    client.taskrouter.v1.workspaces('WS...').workers('WK...').cumulative_statistics()

    New TaskRouter Pattern:

    client.taskrouter.v1.workspaces('WS...').workers.cumulative_statistics()
    from twilio.twiml.voice_response import VoiceResponse
    resp = VoiceResponse()
    say = resp.say("Hello")
    say.emphasis("you")
  9. Use named arguments for Chat Message creation

    main

    In version 6.7.x and later, the body parameter for creating Chat messages must be passed as a named argument. This change was made to support sending media (via media_sid) alongside or instead of text.

    Old way (6.6.x):

    client.chat.v2.services('IS123').channels('CH123').messages.create("this is the body")

    New way (6.7.x+):

    client.chat.v2.services('IS123').channels('CH123').messages.create(body="this is the body")
    from twilio.rest import Client
    
    client = Client('AC123', 'auth')
    client.chat.v2.services('IS123').channels('CH123').messages.create(body="this is the body")
  10. Perform asynchronous API requests

    main

    By default, the Twilio Client performs synchronous requests. For non-blocking, asynchronous operations, use the AsyncTwilioHttpClient and the corresponding *_async methods (e.g., create_async).

    import asyncio
    from twilio.http.async_http_client import AsyncTwilioHttpClient
    from twilio.rest import Client
    
    async def main():
        account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        auth_token  = "your_auth_token"
        http_client = AsyncTwilioHttpClient()
        client = Client(account_sid, auth_token, http_client=http_client)
    
        message = await client.messages.create_async(to="+12316851234", from="+15555555555",
                                                     body="Hello there!")
    
    asyncio.run(main())
  11. Upgrade to twilio-python 9.x.x

    main
    Version 9.0.0 is a major release that introduces support for the application/json content type in request bodies. The library is now auto-generated via OpenAPI to ensure consistency and faster feature delivery. This version is designed to be a drop-in replacement with no breaking changes to existing APIs.