Package: twilio
twilio-pythonDocumentationThe documentation for the Twilio API can be foundhere.The Python library documentation can be foundhere.Versionstwilio-pythonuses a modified version ofSemantic Versioningfor all changes.See this documentfor details.Supported Python VersionsThis library supports the following Python implementations:Python 3.7Python 3.8Python 3.9Python 3.10Python 3.11InstallationInstall from PyPi usingpip, a
package manager for Python.pip3installtwilioIf pip install fails on Windows, check the path length of the directory. If it is greater 260 characters then enableLong Pathsor choose other shorter location.Don't have pip installed? Try installing it, by running this from the command
line:curlhttps://bootstrap.pypa.io/get-pip.py|pythonOr, you candownload the source code
(ZIP)fortwilio-python, and then run:python3setup.pyinstallInfoIf the command line gives you an error message that says Permission Denied, try running the above commands withsudo(e.g.,sudo pip3 install twilio).Test your installationTry sending yourself an SMS message. Save the following code sample to your computer with a text editor. Be sure to update theaccount_sid,auth_token, andfrom_phone number with values from yourTwilio account. Thetophone number will be your own mobile phone.fromtwilio.restimportClient# Your Account SID and Auth Token from console.twilio.comaccount_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"auth_token="your_auth_token"client=Client(account_sid,auth_token)message=client.messages.create(to="+15558675309",from_="+15017250604",body="Hello from Python!")print(message.sid)Save the file assend_sms.py. In the terminal,cdto the directory containing the file you just saved then run:python3send_sms.pyAfter a brief delay, you will receive the text message on your phone.WarningIt's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check outHow to Set Environment Variablesfor more information.Use the helper libraryAPI CredentialsTheTwilioclient needs your Twilio credentials. You can either pass these directly to the constructor (see the code below) or via environment variables.Authenticating with Account SID and Auth Token:fromtwilio.restimportClientaccount_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"auth_token="your_auth_token"client=Client(account_sid,auth_token)Authenticating with API Key and API Secret:fromtwilio.restimportClientapi_key="XXXXXXXXXXXXXXXXX"api_secret="YYYYYYYYYYYYYYYYYY"account_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"client=Client(api_key,api_secret,account_sid)Alternatively, aClientconstructor without these parameters will
look forTWILIO_ACCOUNT_SIDandTWILIO_AUTH_TOKENvariables inside the
current environment.We suggest storing your credentials as environment variables. Why? You'll never
have to worry about committing your credentials and accidentally posting them
somewhere public.fromtwilio.restimportClientclient=Client()Specify Region and/or EdgeTo take advantage of Twilio'sGlobal Infrastructure, specify the target Region and/or Edge for the client:fromtwilio.restimportClientclient=Client(region='au1',edge='sydney')AClientconstructor without these parameters will also look forTWILIO_REGIONandTWILIO_EDGEvariables inside the current environment.Alternatively, you may specify the edge and/or region after constructing the Twilio client:fromtwilio.restimportClientclient=Client()client.region='au1'client.edge='sydney'This will result in thehostnametransforming fromapi.twilio.comtoapi.sydney.au1.twilio.com.Make a Callfromtwilio.restimportClientaccount_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"auth_token="your_auth_token"client=Client(account_sid,auth_token)call=client.calls.create(to="9991231234",from_="9991231234",url="http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient")print(call.sid)Get data about an existing callfromtwilio.restimportClientaccount_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"auth_token="your_auth_token"client=Client(account_sid,auth_token)call=client.calls.get("CA42ed11f93dc08b952027ffbc406d0868")print(call.to)Iterate through recordsThe library automatically handles paging for you. Collections, such ascallsandmessages, havelistandstreammethods that page under the hood. With bothlistandstream, you can specify the number of records you want to receive (limit) and the maximum size you want each page fetch to be (page_size). The library will then handle the task for you.listeagerly fetches all records and returns them as a list, whereasstreamreturns an iterator and lazily retrieves pages of records as you iterate over the collection. You can also page manually using thepagemethod.Use thelistmethodfromtwilio.restimportClientaccount_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"auth_token="your_auth_token"client=Client(account_sid,auth_token)forsmsinclient.messages.list():print(sms.to)Asynchronous API RequestsBy default, the Twilio Client will make synchronous requests to the Twilio API. To allow for asynchronous, non-blocking requests, we've included an optional asynchronous HTTP client. When used with the Client and the accompanying*_asyncmethods, requests made to the Twilio API will be performed asynchronously.fromtwilio.http.async_http_clientimportAsyncTwilioHttpClientfromtwilio.restimportClientasyncdefmain():account_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"auth_token="your_auth_token"http_client=AsyncTwilioHttpClient()client=Client(account_sid,auth_token,http_client=http_client)message=awaitclient.messages.create_async(to="+12316851234",from_="+15555555555",body="Hello there!")asyncio.run(main())Enable Debug LoggingLog the API request and response data to the console:importloggingclient=Client(account_sid,auth_token)logging.basicConfig()client.http_client.logger.setLevel(logging.INFO)Log the API request and response data to a file:importloggingclient=Client(account_sid,auth_token)logging.basicConfig(filename='./log.txt')client.http_client.logger.setLevel(logging.INFO)Handling ExceptionsVersion 8.x oftwilio-pythonexports an exception class to help you handle exceptions that are specific to Twilio methods. To use it, importTwilioRestExceptionand catch exceptions as follows:fromtwilio.restimportClientfromtwilio.base.exceptionsimportTwilioRestExceptionaccount_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"auth_token="your_auth_token"client=Client(account_sid,auth_token)try:message=client.messages.create(to="+12316851234",from_="+15555555555",body="Hello there!")exceptTwilioRestExceptionase:print(e)Generating TwiMLTo control phone calls, your application needs to outputTwiML.Usetwilio.twiml.Responseto easily create such responses.fromtwilio.twiml.voice_responseimportVoiceResponser=VoiceResponse()r.say("Welcome to twilio!")print(str(r))<?xml version="1.0" encoding="utf-8"?><Response><Say>Welcometotwilio!</Say></Response>Other advanced examplesLearn how to create your own custom HTTP clientDocker ImageTheDockerfilepresent in this repository and its respectivetwilio/twilio-pythonDocker image are currently used by Twilio for testing purposes only.Getting helpIf you need help installing or using the library, please check theTwilio Support Help Centerfirst, andfile a support ticketif you don't find an answer to your question.If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!