Introduction
This tutorial will show you how to receive SMS messages in Python with help from the Vonage API.
Vonage has two different APIs for receiving SMS: the SMS API used strictly for SMS messaging and the Messages API allowing you to use other channels like WhatsApp. In this tutorial, we’ll be using the Messages API to receive inbound SMS messages with Python.
The inbound SMS messages will be received via a publicly accessible webhook. This article will walk you through how to set up that webhook and connect it with your Vonage account.
Prerequisites
To create a Python app for receiving inbound SMS messages, you will need the following programs.
Python
Python is needed to use the Flask library. Visit the official Python downloads page to download a Python version that works for you.
Flask
You will use Flask to write your webhook. Before installing Flask, create your project directory and navigate into it as follows:
mkdir receive_sms
cd receive_sms
You can install Flask with the pip package manager that comes installed with Python. Use the following terminal command to install Flask inside the newly created folder.
pip install flask
Vonage API
To use the Vonage Messages API, you will need a Vonage API account. Access your Vonage API Dashboard to locate your API Key and API Secret, which can be found at the top of the page.
Vonage CLI
The Vonage CLI package can be used to purchase a Vonage virtual number instead of purchasing on your dashboard UI. It can also be used to send a test SMS.
Install the Vonage CLI globally in your terminal by running this command:
To purchase a Vonage phone number via CLI, first set up your API credentials with vonage config:set --apiKey=XXXXXX --apiSecret=XXXXXX
, then search for available numbers with vonage numbers:search [Alpha-2 Country Code]
and buy one using vonage numbers:buy [Number] [Country Code]
.
Alternatively, acquire a number directly through the Buy Number section on your dashboard.
How to Receive SMS Messages in Python with the Vonage API
Once you have successfully installed Python, Flask, and the Vonage CLI, you are ready to get started. Below, we’ll explain how to use these tools so that Python can receive text messages from the Vonage API. To create a Python application that receives SMS messages, simply follow these 4 steps:
Create a webhook for inbound SMS
Make the webhook URL publicly accessible
Configure your Vonage account
Send and receive a test SMS message
1. Create the Webhook for Inbound SMS
The first step to receiving an SMS in Python is to create a webhook for inbound text messages.
Upon receiving an SMS message on your Vonage account, Vonage verifies whether you have a webhook in place. If it finds a webhook, it can forward the message to your application. You may configure the webhook to work for a single number or all the numbers in your account.
To handle incoming messages, your webhook handler will be designed to accept a POST
request. To facilitate this, you will create a Flask endpoint dedicated to handling the incoming requests.
Create an sms-receive.py
file in your Flask project and add the following code:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/webhooks/inbound-message", methods=['POST'])
def inbound_message():
if request.is_json:
data = request.get_json()
print(data)
else:
data = dict(request.form) or dict(request.args)
print(data)
return "200"
if __name__ == '__main__':
app.run(host="", port=3000)
Let’s unpack this to see how this code functions. In the previous code snippet:
You defined a webhook endpoint named
/webhooks/inbound-message
. This endpoint is responsible for receiving and parsing the data contained within inbound message payloads.
@app.route("/webhooks/inbound-message", methods=['POST'])
def inbound_message():
The
request.get_json()
method is utilized to verify whether the request is in JSON format.In case the request is not in JSON format, the key/value pairs within the request body or URL query string are retrieved usingrequest.form
andrequest.args
, respectively.
if request.is_json:
data = request.get_json()
The request data is parsed and stored in the
data
variable, and then printed to the terminal usingprint
.
data = request.get_json()
print(data)
Finally, you indicate that the application be run and served in port 3000
.
if __name__ == '__main__':
app.run(host="", port=3000)
Make Webhook URL Publicly Accessible
The webhook endpoint for your Python application will need to be accessible over the public internet. This way, Vonage APIs can request your webhook endpoint when it receives an SMS message.
Usually in production mode, you would need a server with a public domain to append the endpoint. However, for testing in development mode, we will use ngrok
to mimic the server environment. We have a tutorial that explains in-depth how to use ngrok
when testing Vonage APIs.
You can download or install ngrok from the official website.
Next, launch ngrok on your terminal:
Once ngrok is launched, it will generate a public URL for you similar to the following:
Note:
If you are on the free plan, the URL changes when you restart the
ngrok
server.In the free plan, an ngrok server session lasts for 1 hour. If you wish to start a new session, launch the server again to receive a new public URL.
You can then append your endpoint to the newly generated ngrok URLs to form your webhook URLs like this:
Now, you will need this URL when creating your application in the next section of this tutorial.
Configure Vonage Account
Next, you’ll need to configure your Vonage Account to use the correct API for SMS messaging. We’ll be using the Messages API for our application instead of the SMS API.
To adjust this setting, go to your dashboard settings page. Then, go to the SMS settings section to select Messages API.
Next, go to the applications page to create an application.
Click the + Create application button.
Supply your desired name in the Name field.
In the Capabilities section, select Messages and input your webhook Inbound URL. You can check out our tutorial on how to set up the Status URL for accepting the delivery status of outbound SMS.
Click Generate new Application to complete the process. You will then be redirected to the newly-created application page. On this page, you can link your number or pay for a virtual number.
4. Send and Receive a Test SMS Message
Your application is now ready to receive inbound SMS messages!! Your ngrok server is running in port 3000
, and you have configured your application with a virtual number in your Vonage account.
Now, you can start the Flask application in another terminal window to keep the previous terminal window running with ngrok.
By executing that command, your Flask application will be launched on your local host port 3000
. This port will be automatically detected by ngrok, enabling you to serve your application to the public internet using ngrok's public URL.
Now, use the following Vonage CLI command to send a test SMS to your Vonage number on your terminal.
In the terminal window that is running your Python application, you should see that your webhook received the inbound SMS:
You will also receive the SMS message on your mobile phone like the following screenshot:
Conclusion
Throughout this tutorial, you've discovered the process of receiving inbound SMS messages using Python.
Now, you can integrate the Vonage Messages API into your Python applications and start using these apps to handle inbound text messages.
Further Reading
Check out Vonage’s resources to learn more about the Messages API:
Did you enjoy this tutorial? Did you get stuck? Reach out on Twitter or the Vonage Community Slack. We’re excited to see what you’re building!
Jẹ́káyinOlúwa is a software craftsman and product manager passionate about technology and its impact on people. He works on product management, backend development, DevOps, technical writing, and community strategy. He enjoys dealing in the intersection of software, design, and human interaction. He likes reading and music.