How to Send SMS from API or Backend 📲

Sending SMS is one of the essential features for any app’s backend. I’ve recently started working on an app and I needed an SMS service to send transactional SMS

After some research, I found Textlocal to be a viable option with decent pricing, automated campaigns, automated reports, and good support. Their approval process was pretty fast as well.

SMS approval process for developers

Most beginner developers might not know the process of SMS approval. It is not pretty straight-forward. There are some rules for what SMS can be sent, what ID you’ll be assigned, and at what time the SMS can be sent. Let’s check it out

There are different rules in different countries with regard to SMS depending on the telecom authority of that country. I’m explaining these from India’s perspective.

Types of SMS

There are two types of SMS which can be sent programmatically.

  1. Promotional SMS
  2. Transactional SMS

Promotional SMS

Promotional SMS is used to send promotions, offers, discounts etc. to the users. This SMS is not really important for users.

There’s no approval needed for promotional SMS. You can simply register with any SMS provider and start sending single or bulk SMS from the service provider’s web dashboard.

This is the type of SMS that could lead to spam so there are some rules with promotional SMS

  • Promotional SMS can only be sent between 9 AM and 9 PM
  • Promotional SMS is not sent to DND (Do not disturb) numbers
  • Promotional  SMS is sent from a random ID which is available from the service provider at the time of sending SMS

Transactional SMS

Transactional SMS is used to send welcome SMS, verification codes, OTPs, Order status SMS etc. Transactional SMS doesn’t have any limit on the timings and the SMS will also be sent to DND numbers.

Transactional SMS has an approval process. You need to send a few documents to the service provider. Documents are as follows :

1. Opt-in permission in the privacy policy
2. Letter of consent

Here’s an example of opt-in proof

sms opt-in proof example
Opt-in proof

You’ll receive a sample format for letter of consent in which you can fill your name, your business name, sign it and send it.

You should also mention the 6 letter ID that you would like to use as sender ID. It should be unique.

The service provider will verify your documents and approve your account for transactional SMS. This is the initial approval process.

Transactional SMS templates

Only pre-approved SMS templates can be sent as transactional SMS. This limit is to make sure that users won’t use the transactional SMS to send promotional SMS content.

Here’s an example of SMS template for sending verification code or OTP

SMS template example
SMS template example

Once the template is approved, You can start sending SMS from the service provider’s dashboard or using their API.

Many Service providers have client libraries and SDKs to make it easier for the developers to send SMS programmatically.

Send SMS using Node.js

I’m using Text Local as the SMS service provider and we have an Express Node.js backend. Let me show you how we send SMS from API in our Express app. Check out the code below.

//This code was posted for an article at
const axios = require("axios");
const tlClient = axios.create({
baseURL: "",
params: {
apiKey: "YOUR API KEY", //Text local api key
const smsClient = {
sendPartnerWelcomeMessage: user => {
if (user && && {
const params = new URLSearchParams();
params.append("numbers", [parseInt("91" +]);
`Hi ${},
Welcome to iWheels, Download our app to get bookings from our customers with better pricing.`
);"/send", params);
sendVerificationMessage: user => {
if (user && {
const params = new URLSearchParams();
params.append("numbers", [parseInt("91" +]);
`Your iWheels verification code is ${user.verifyCode}`
);"/send", params);
module.exports = smsClient;
// Now import the client in any other file or wherever required and run these functions
// const smsClient = require("./smsClient");
// smsClient.sendVerificationMessage(user)
view raw smsClient.js hosted with ❤ by GitHub

SMS Code explanation

The service provider that I’m using has a REST API. All we need to do is send a POST request to the API with API key, sender ID, phone number and the message body

Read Text Local documentation here

I’m using Axios as the Rest client. We don’t need any external client in this case but Axios helps us in creating a client instance with default params so that the API URLAPI key and Sender ID need not be passed in every request manually.

I’ve created a file named smsClient.js where multiple functions are defined for different SMS. Now, All we need to do is import the smsClient and call appropriate functions wherever required.

Send SMS PHP example

	$apiKey = urlencode('Your apiKey');
	// Message details
	$numbers = array(918123456789, 918987654321);
	$sender = urlencode('YOUR SENDER ID');
	$message = rawurlencode('This is your message');
	$numbers = implode(',', $numbers);
	// Prepare data for POST request
	$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
	// Send the POST request with cURL
	$ch = curl_init('');
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$response = curl_exec($ch);
	// Process your response here
	echo $response;

Send  SMS Python example

#!/usr/bin/env python
import urllib.request
import urllib.parse
def sendSMS(apikey, numbers, sender, message):
    data =  urllib.parse.urlencode({'apikey': apikey, 'numbers': numbers,
        'message' : message, 'sender': sender})
    data = data.encode('utf-8')
    request = urllib.request.Request("")
    f = urllib.request.urlopen(request, data)
    fr =
resp =  sendSMS('apikey', '918123456789',
    'Jims Autos', 'This is your message')
print (resp)

Send SMS Ruby example

require "rubygems"
require "net/https"
require "uri"
require "json"
requested_url = ''
uri = URI.parse(requested_url)
http = Net::HTTP.start(, uri.port)
request =
res = Net::HTTP.post_form(uri, 'apikey' => 'yourApikey', 'message' => 'This is your message', 'sender' => 'Ben', 'numbers' => '918123456789')
response = JSON.parse(res.body)
puts (response)

Send SMS Java example

public class sendSMS {
	public String sendSms() {
		try {
			// Construct data
			String apiKey = "apikey=" + "yourapiKey";
			String message = "&message=" + "This is your message";
			String sender = "&sender=" + "TXTLCL";
			String numbers = "&numbers=" + "918123456789";
			// Send data
			HttpURLConnection conn = (HttpURLConnection) new URL("").openConnection();
			String data = apiKey + numbers + message + sender;
			conn.setRequestProperty("Content-Length", Integer.toString(data.length()));
			final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			final StringBuffer stringBuffer = new StringBuffer();
			String line;
			while ((line = rd.readLine()) != null) {
			return stringBuffer.toString();
		} catch (Exception e) {
			System.out.println("Error SMS "+e);
			return "Error "+e;

Send SMS VBA example

Public Sub Send()
	Dim username As String
	Dim password As String
	Dim result As String
	Dim myURL As String
	Dim Sender As String
	Dim numbers As String
	Dim Message As String
	Dim postData As String
	Dim winHttpReq As Object
	apikey = "yourAPIkey"
	Sender = "YOUR SENDER ID"
	numbers = "918123456789"
	Message = "This is your message"
	Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
	myURL = ""
	postData = "apikey=" + apikey + "&message=" + Message + "&numbers=" + numbers + "&sender=" + Sender
	winHttpReq.Open "POST", myURL, False
	winHttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
	winHttpReq.Send (postData)
	SendSMS = winHttpReq.responseText
End Sub

Send SMS VB.NET example

Imports System.Web
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Resources
Public Class sendSMS
    Public Function sendSMS()
        Dim apikey = "yourAPIkey"
        Dim message = "This is your message"
        Dim numbers = "918123456789"
        Dim strPost As String
        Dim sender = "YOUR SENDER ID"
        Dim url As String = ""
        Dim strPost As String
        strPost = url + "apikey=" + apikey _
        + "&numbers=" + numbers _
        + "&message=" + WebUtility.UrlEncode(message) _
        + "&sender=" + sender
        Dim request As WebRequest = WebRequest.Create(strPost)
        request.Method = "POST"
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(strPost)
        request.ContentType = "application/x-www-form-urlencoded"
        request.ContentLength = byteArray.Length
        Dim dataStream As Stream = request.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
        Dim response As WebResponse = request.GetResponse()
        dataStream = response.GetResponseStream()
        Dim reader As New StreamReader(dataStream)
        Dim responseFromServer As String = reader.ReadToEnd()
        If responseFromServer.Length > 0 Then
            Return responseFromServer
            Return CType(response, HttpWebResponse).StatusDescription
        End If
    End Function
End Class

Send SMS C# example

using System;
using System.Collections.Generic;
using System.Net;
using System.Collections.Specialized;
namespace sendSMS
    class sendSMS
        public string sendSMS()
            String message = HttpUtility.UrlEncode("This is your message");
            using (var wb = new WebClient())
                byte[] response = wb.UploadValues("", new NameValueCollection()
                {"apikey" , "yourapiKey"},
                {"numbers" , "918123456789"},
                {"message" , message},
                {"sender" , "YOUR SENDER ID"}
                string result = System.Text.Encoding.UTF8.GetString(response);
                return result;

Send SMS ASP.NET example

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<script runat="server" language="VB">
    Sub Page_Load(sender As Object, e As EventArgs)
        Dim apikey As String = "YourapiKey"
        Dim SenderName As String = "YOUR SENDER ID"
        Dim Number As String = "918123456789"
        Dim Message As String = "This is an API message"
        Dim URL As String = ""
        Dim PostData As String = "apikey=" & apikey & "&sender=" & SenderName & "&numbers=" & Number & "&message=" & Message
        Dim req As HttpWebRequest = WebRequest.Create(URL)
        req.Method = "POST"
        Dim encoding As New ASCIIEncoding()
        Dim byte1 As Byte() = encoding.GetBytes(PostData)
        req.ContentType = "application/x-www-form-urlencoded"
        req.ContentLength = byte1.Length
        Dim newStream As Stream = req.GetRequestStream()
        newStream.Write(byte1, 0, byte1.Length)
            Dim resp As HttpWebResponse = req.GetResponse()
            Dim sr As New StreamReader(resp.GetResponseStream())
            Dim results As String = sr.ReadToEnd()
            html.Text = results
        Catch wex As WebException
	  Response.Write("SOMETHING WENT AWRY!
Status: " & wex.Status & "Message: " & wex.Message & "")
        End Try
    End Sub

Wrapping up

It doesn’t matter which language you are using, It is ultimately a simple POST request with the data as params. Almost all SMS service providers have a REST API. Read the documentation once and implement it!

Happy texting 😍📲

Recent articles :

Speech recognition and synthesis with simple JavaScript

Sarcastic web services and websites that actually exist😂

Ranjith kumar
0 0 votes
Article Rating
Notify of

Newest Most Voted
Inline Feedbacks
View all comments
shahiduzzaman foysal
shahiduzzaman foysal
5 years ago

i dont get javascript using api send sms

Jed Ng
5 years ago

Hi Ranjit, your blog article for sending SMS came up on my newsfeed and I wanted to reach out.

First off, I thought is a pretty cool idea. I also wanted to share that you can access Telesign or Nexmo APIs, or any of our 8000 other APIs via Rakuten RapidAPI ( we’re the world’s largest API Marketplace with 500k developers. We’d love to get on a call and do a demo for you.

We’d be happy to offer you a free coupon credit. You can claim it here

4 years ago

very interesting and inspiring article.

coding is my passion.

2 years ago

very interesting and inspiring article.