We will implement Twilio rest api to send message using python 3.Twilio is providing a Cloud communications platform for building SMS, Voice & Messaging. You can build and send SMS, Voice & Messaging via globally available cloud API.
You can use Twilio to integrating phone calls, text messages and IP voice communications into web applications, mobile and traditional phones. They are providing telephony infrastructure via web service API. The Twilio API is simple to use, powerful, and endlessly scalable.
You can get started with a free trial or purchase a plan.
Table of Contents
Twilio API Using Python 3
I am using python 3 and flask rest micro-framework to access Twilio API. We will create a simple API wrapper to send messages using Twilio API. I am assuming, You are aware to install python and flask.I have already shared Consuming a RESTful API with Python and Flask.
How To Register App With Twilio
We will register an account with Twilio, after successful registration, They are providing account_sid and auth_token.
How To Install Twilio With Python
We will install the Twilio package using the python pip command –
pip install twilio
Make Route Entry Into Python
Now, We will create a route entry into the main python file –
api.add_resource(SendData, "/send_data")
Create handler method into controller class, imported Twilio libs and created client using account_sid
and auth_token
.
Handler Method in Python
from twilio.rest import Client class SendData(Resource): def get(Resource): try: account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # change the "from_" number to your Twilio number and the "to" number # to the phone number you signed up for Twilio with, or upgrade your # account to send SMS to any phone number message = client.messages.create(to="+XXXXXXXXXXXXX", from_="+XXXXXXXXXXXXX", body="Hello from Python!") return jsonify({"results": message.sid, "code" : 200, "message" : "Successfully! Mesage has been sent"}) except (ValueError) as e: return e
Now, run python and open into the browser http://localhost:5000/send_data, if everything is perfect, then you will get a success message and the message will send to the target number.