Wednesday, October 05, 2016

Python - Twilio SMS Implementation in REST

Twilio is a cloud communication company which allows software developers to programmatically make and receive phone calls or text messages using its web service APIs. In this blog I am going to show you a simple example I created in Python for SMS sending through REST calls.

Requirements:
  • Python 2.7+
  • pip installed
  • flask, twilio modules are installed
  • A twilio account, and you have at least registered a phone number
The source code is very straight forward, you import the "TwilioRestClient" from twilio rest module, then you define your twilio account sid, token then initialize a twilio client. By using flask, you can have a simple "http://example.com/send_code" web service up and running in any public accessable server, for example, a AWS instance which has a public IP, or even you localhost.

Then you start your flask app by running:
$ python run_app.py
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: xxx-658-8xx

Then you post some data to "http://localhost:5000/send_code", for example:
$ curl -H "Content-Type: application/json" -X POST -d '{"cellphone_number":"xxxxxxxx"}' http://127.0.0.1:5000/send_code
Message has been sent!

Replace "xxxxxxx" with your own cellphone number and expecting a SMS text msg!

You will see a message from "run_app.py" terminal:
127.0.0.1 - - [05/Oct/2016 14:37:45] "POST /send_code HTTP/1.1" 200 -

Source code:
https://bitbucket.org/tonylixu/twilio-sms-python

No comments: