- Notifications
You must be signed in to change notification settings - Fork772
A Python module for communicating with the Twilio API and generating TwiML.
License
twilio/twilio-python
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The documentation for the Twilio API can be foundhere.
The Python library documentation can be foundhere.
twilio-python
uses a modified version ofSemantic Versioning for all changes.See this document for details.
This library supports the following Python implementations:
- Python 3.7
- Python 3.8
- Python 3.9
- Python 3.10
- Python 3.11
- Python 3.12
- Python 3.13
Install from PyPi usingpip, apackage manager for Python.
pip3 install twilio
If pip install fails on Windows, check the path length of the directory. If it is greater 260 characters then enableLong Paths or choose other shorter location.
Don't have pip installed? Try installing it, by running this from the commandline:
curl https://bootstrap.pypa.io/get-pip.py| python
Or, you candownload the source code(ZIP) fortwilio-python
, and then run:
python3 setup.py install
InfoIf the command line gives you an error message that says Permission Denied, try running the above commands with
sudo
(e.g.,sudo pip3 install twilio
).
Try 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. Theto
phone 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,cd
to the directory containing the file you just saved then run:
python3 send_sms.py
After 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 Variables for more information.
We are introducing Client Credentials Flow-based OAuth 2.0 authentication. This feature is currently in beta and its implementation is subject to change.
API exampleshere
Organisation API exampleshere
TheTwilio
client 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, aClient
constructor without these parameters willlook forTWILIO_ACCOUNT_SID
andTWILIO_AUTH_TOKEN
variables inside thecurrent environment.
We suggest storing your credentials as environment variables. Why? You'll neverhave to worry about committing your credentials and accidentally posting themsomewhere public.
fromtwilio.restimportClientclient=Client()
To take advantage of Twilio'sGlobal Infrastructure, specify the target Region and Edge for the client:
Note: When specifying a
region
parameter for a helper library client, be sure to also specify theedge
parameter. For backward compatibility purposes, specifying aregion
without specifying anedge
will result in requests being routed to US1.
fromtwilio.restimportClientclient=Client(region='au1',edge='sydney')
AClient
constructor without these parameters will also look forTWILIO_REGION
andTWILIO_EDGE
variables 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 thehostname
transforming fromapi.twilio.com
toapi.sydney.au1.twilio.com
.
fromtwilio.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)
fromtwilio.restimportClientaccount_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"auth_token="your_auth_token"client=Client(account_sid,auth_token)call=client.calls.get("CA42ed11f93dc08b952027ffbc406d0868")print(call.to)
The library automatically handles paging for you. Collections, such ascalls
andmessages
, havelist
andstream
methods that page under the hood. With bothlist
andstream
, 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.
list
eagerly fetches all records and returns them as a list, whereasstream
returns an iterator and lazily retrieves pages of records as you iterate over the collection. You can also page manually using thepage
method.
page_size
as a parameter is used to tell how many records should we get in every page andlimit
parameter is used to limit the max number of records we want to fetch.
fromtwilio.restimportClientaccount_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"auth_token="your_auth_token"client=Client(account_sid,auth_token)forsmsinclient.messages.list():print(sms.to)
client.messages.list(limit=20,page_size=20)
This will make 1 call that will fetch 20 records from backend service.
client.messages.list(limit=20,page_size=10)
This will make 2 calls that will fetch 10 records each from backend service.
client.messages.list(limit=20,page_size=100)
This will make 1 call which will fetch 100 records but user will get only 20 records.
By 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*_async
methods, 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())
Log 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)
Version 8.x oftwilio-python
exports an exception class to help you handle exceptions that are specific to Twilio methods. To use it, importTwilioRestException
and 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)
To control phone calls, your application needs to outputTwiML.
Usetwilio.twiml.Response
to 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>Welcome to twilio!</Say></Response>
TheDockerfile
present in this repository and its respectivetwilio/twilio-python
Docker image are currently used by Twilio for testing purposes only.
If you need help installing or using the library, please check theTwilio Support Help Center first, andfile a support ticket if 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!
About
A Python module for communicating with the Twilio API and generating TwiML.
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.