Friday, December 27, 2024
Google search engine
HomeLanguagesSend Text messages to any mobile number using Fast2SMS API in Python

Send Text messages to any mobile number using Fast2SMS API in Python

This article is going to be about how can we send text messages using Python. We will be using Fast2SMS API to send messages. You don’t need to install any Python package for this purpose.

First, you need a Fast2SMS account. You can sign up for Fast2SMS from here. Now, go to Dev API option and copy the API Authorization Key. This API key is generated by Fast2SMS, however, you can regenerate the API key if you want to. Now, all you have to do is to make a POST request to Fast2SMS API with your API key, message, recipient, etc. and it will send your SMS.

So, to make requests to the API, we need to use the requests module, and to read the data returned by the API, we need json module. So, first Let’s import them.

Python3




# import required module
import requests
import json


Now, We will create two dictionaries, one for the SMS data and another for the headers.

Python




# mention url
  
  
# create a dictionary
my_data = {
     # Your default Sender ID
    'sender_id': 'FSTSMS'
    
     # Put your message here!
    'message': 'This is a test message'
    
    'language': 'english',
    'route': 'p',
    
    # You can send sms to multiple numbers
    # separated by comma.
    'numbers': '9999999999, 7777777777, 6666666666'    
}
  
# create a dictionary
headers = {
    'authorization': 'YOUR API KEY HERE',
    'Content-Type': "application/x-www-form-urlencoded",
    'Cache-Control': "no-cache"
}


Now, we are ready to post our data to the API.

Python3




# make a post request
response = requests.request("POST",
                            url,
                            data = my_data,
                            headers = headers)
#
load json data from source
returned_msg = json.loads(response.text)
  
# print the send message
print(returned_msg['message'])


Output:

['Message sent successfully to NonDND numbers']

If the message is sent successfully, It will print a success message. Your mobile number will be displayed to the recipient with your message.

In case of an error, it will print the Error message.

For example, if your API key is changed or you have entered the wrong API key, the following error message will be printed.

Invalid Authentication, Check Authorization Key

RELATED ARTICLES

Most Popular

Recent Comments