Recently, industry-leading programmable communications provider Twilio partnered with RapidAPI in order to make their excellent services that much more accessible. Twilio’s services allow applications to programmatically make and receive phone calls, send and receive text messages, and perform other communication services via its RESTful APIs.
We’ll be looking at how to interact with Twilio’s SMS API via RapidAPI using Python’s Requests library, and then we’ll apply what we cover in the RapidAPI UI to a simple Flask app that will fire off a text message when it receives an HTTP GET request.
Today, we’re going to:
- Sign up for Twilio on the Rapid API platform
- Collect relevant account details
- Purchase a number from Twilio from which to send a text message
- Send your first text message!
- Put all this new knowledge and more into practice with a simple Flask app
How To Send SMS with Python
1. Sign up for Twilio on RapidAPI
Without further ado, let’s go ahead and sign up. Head over to https://rapidapi.com/twilio/api/twilio-sms/pricing in your browser, sign up if you haven’t already, and click “Subscribe.”
Note: Sending a text message incurs a cost described in credits worth $0.0001 cents. In addition to the varying cost of sending text messages, you will also need to purchase a phone number from Twilio, which will cost $1.00.
2. Get your account particulars:
Then, you can fetch your account details. Simply select the topmost GET request in the left sidebar. Then, once logged in and subscribed, you can click the blue button shown below to execute the call.
3. Buy a phone number from Twilio:
Then, you can purchase a phone number from which to send your text messages. Simply select the endpoint POST Buy a Phone Number in the sidebar navigation, enter the required parameters, and click ol’ blue again up at the top.
Purchasing a number from Twilio requires three parameters:
Note: If you don’t have your SID yet, or if you just don’t have it handy for a test, you can simply pass an `a` in the request, and RapidAPI will autocomplete it for you when it passes the request to Twilio.
4. Send your first text:
Alright, let’s kick the tires and see if it runs! We’ll need to pass the following:
If all goes well, you should receive your first text message within just a few moments.
5. Build something with it:
Finally, we’ll build a simple Flask app that listens for a GET request, and fires off a pre-written text message one comes in. I plan to use this to notify me when some silly long process (i.e. db ingest) completes. 🙂
First, let’s create a file called `app.py`. Then we’ll handle our imports. You will need to import Flask and the Python requests library. If you don’t have Flask installed, don’t let that deter you. Pip has you covered. To install, simply run:
pip3 install flask
We can also set the variables that we are likely to want to change in the future as global variables, like so.
from flask import flask import requests X_RAPID_API_KEY = 'x_rapid_api_key' TWILIO_PHONE_NUMBER = 'phone_number_purchased_from_twilio' TO_NUMBER = 'recipients_phone_number' SID = 'your_sid' MESSAGE_BODY = 'Is your number {}? jk haha. I'm done.'.format(TO_NUMBER)
Notice my hilarious use of Python3’s string formatting. The curly braces define the location in the string that the `format()` value will be placed when the app runs.
Next, we’ll create our app proper. In order to do so, we’ll have to instantiate the Flask class. This leaves us with this magical variable `app` that lets us do all sorts of neat stuff — not least of which is exposing an API that will listen for our requests.
app = Flask(__name__) if __name__ == '__main__': app.run()
Now that that’s out of the way, let’s create the first route that our app will handle. To do so, we’ll need to define a route and the HTTP request methods that will be allowed at that endpoint.
You can see below that I have defined a route `/notify`, which will accept an HTTP GET request.
Next, we’ll need to write a function that will be executed when our app receives said GET request. This is where all of that progress we made above comes back into the picture.
@app.route('/notify', methods=['GET']) def notify(): url = "https://twilio-sms.p.rapidapi.com/2010-04-01/Accounts/{}/Messages.json".format(SID) params = {"from":TWILIO_PHONE_NUMBER,"body":MESSAGE_BODY,"to":TO_NUMBER} headers = { 'x-rapidapi-host': "twilio-sms.p.rapidapi.com", 'x-rapidapi-key': X_RAPID_API_KEY, 'content-type': "application/x-www-form-urlencoded" } response = requests.post(url, headers=headers, params=params) return '' if __name__ == '__main__': app.run()
Notice that we’ve included the required params in our call to the Twilio SMS API. We are returning an empty string, because it will make Flask happy, and we don’t really care about what response the requester gets back. Instead, we are mainly interested in getting the text message sent to the person who needs to be notified on behalf of the requester. And once we fire off our POST request to Twilio, we’ve done our part. The rest is up to Twilio’s magical API!
Test it:
So, my motivation behind this is at least a little selfish. I plan to run this app locally and then to simply add a GET request to any old script that points at `http//:0.0.0.0:5000/notify`, so that I can leave long-running scripts unattended, but I’ll get a heads up when they finish.
To replicate this use case, we can do the following:
- In your terminal, run `python3 app.py`.
- Create a second file called `fake_process.py`.
- Paste in the following code.
- Open a second terminal, cd into your working directory, and run `python3 fake_process.py`
- It will count to 10,000 to replicate the delay that would come with a real process running, and then send the GET request our API is listening for.
- Receive a text message from yourself like a boss!!!
import requests def fake_process(): count = 0 while count < 10000: counter += 1 if counter == 10000: response = requests.get('https://0.0.0.0:5000/notify') print(response.status_code) fake_process()
And that’s it! You now have a nifty notifier app thingy, and (more importantly) you’re ready to go build something exceptional with your newfound knowledge. Happy building!
Next steps:
Explore all of Twilio’s services that are now offered on RapidAPI’s platform.
Twilio Lookup — Reduce undeliverable messages, identify local-friendly number formats, and resolve caller names with Twilio Lookup. Find phone types, carriers, and more.
Twilio Verify Phone Number — Twilio Verify API makes it simple to add phone number verification to your web application. It supports codes sent via voice and SMS.
How to Use Twilio on RapidAPI
Here’s a short video, showing you how to use the Twilio API (with RapidAPI) and integrating it into your app:
Related Resources:
- How to use an API with Python
- How to build an API in Python (Flask)
- How to Create an API in Python (Django Framework)
- How to use the OWM API in Python
- Best SMS APIs
- How to Send SMS with PHP (Twilio or Nexmo)
- How to use the Twilio API with Ruby
Leave a Reply