SMS REST API Quick start

Invents, designs, develops!

Getting started:

  • Create an account for free

  • Explore our professional SMS gateway platform

  • Explore API documentation

  • Test your app with our SMS REST API

Send an SMS message: Full example

You can start by copying this example and you’ll be up and running for sending an SMS message to multiple recipients in just a few clicks!

Just change the username and password strings, add a valid recipient list and execute the code!

The listed example authenticates the user using username and password with the Authentication API and then sends an SMS calling the Send SMS API.

Copy code
echo 'Full example not available for shell'
Copy code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
// This example requires Gson configured in the build path (for JSON support):
// https://github.com/google/gson
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
    public static final String BASEURL = "http://app.gateway.smsend.it/API/v1.0/REST/";
    public static final String MESSAGE_HIGH_QUALITY = "N";
    public static final String MESSAGE_MEDIUM_QUALITY = "L";
    public static final String MESSAGE_LOW_QUALITY = "LL";
    public static void main(String[] args) {
        try {
            String[] authKeys = login("username", "password");
            SendSMSRequest sendSMS = new SendSMSRequest();
            sendSMS.setMessage("Hello world!");
            sendSMS.setMessageType(MESSAGE_HIGH_QUALITY);
            sendSMS.addRecipient("+39123456789");
            // Send it in 5 minutes!
            sendSMS.setScheduledDeliveryTime(new Date(System.currentTimeMillis() + (60000L * 5L)));
            sendSMS(authKeys, sendSMS);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /* 
    * This object is used to create an SMS message sending request.
    * The JSon object is then automatically created
    * starting from an instance of this class, using GSon.
    */
    public static class SendSMSRequest {
        // The message body
        private String message;
        // The message type
        private String message_type = MESSAGE_HIGH_QUALITY;
        // Should the API return the remaining credits?
        private boolean returnCredits = false;
        // The list of recipients
        private List<String> recipient = new ArrayList<>();
        // The sender Alias (TPOA)
        private String sender = null;
        // Postpone the SMS message sending to the specified date
        private Date scheduled_delivery_time = null;
        public String getMessage() {
            return message;
        }
        public void setMessage(String message) {
            this.message = message;
        }
        public String getMessageType() {
            return message_type;
        }
        public void setMessageType(String messageType) {
            this.message_type = messageType;
        }
        public boolean isReturnCredits() {
            return returnCredits;
        }
        public void setReturnCredits(boolean returnCredits) {
            this.returnCredits = returnCredits;
        }
        public List<String> getRecipient() {
            return recipient;
        }
        public String getSender() {
            return sender;
        }
        public void setSender(String sender) {
            this.sender = sender;
        }
        public Date getScheduledDeliveryTime() {
            return scheduled_delivery_time;
        }
        public void setScheduledDeliveryTime(Date scheduled_delivery_time) {
            this.scheduled_delivery_time = scheduled_delivery_time;
        }
        public void addRecipient(String recipient) {
            this.recipient.add(recipient);
        }
    }
    
    /*
    * This class represents the API Response. 
    * It is automatically created starting from the JSON object
    * returned by the server, using GSon
    */
    public static class SendSMSResponse {
        private String result;
        private String order_id;
        private int total_sent;
        private int remaining_credits;
        private String internal_order_id;
        public String getResult() {
            return result;
        }
        public String getOrderId() {
            return order_id;
        }
        public int getTotalSent() {
            return total_sent;
        }
        public int getRemainingCredits() {
            return remaining_credits;
        }
        public String getInternalOrderId() {
            return internal_order_id;
        }
        public boolean isValid() {
            return "OK".equals(result);
        }
    }
    
    /*
    * Authenticates the user given it's username and password.
    * Returns the pair user_key, Session_key
    * @param username The user username
    * @param password The user password
    * @return A list with 2 strings. Index 0 is the user_key, index 1 is the Session_key
    * @throws IOException If an error occurs
    */
    private static String[] login(String username, String password) throws IOException {
        URL url = new URL(BASEURL + "/login?username=" + username + "&password=" + password);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = "";
        String output;
        while ((output = br.readLine()) != null) {
            response += output;
        }
        conn.disconnect();
        String[] parts = response.split(";");
        return parts;
    }

    /*
    * Sends an SMS message
    * @param authKeys The pair of user_key and Session_key
    * @param sendSMS The SendSMS object
    * @throws IOException If an error occurs
    */
    private static boolean sendSMS(String[] authKeys, SendSMSRequest sendSMS) throws IOException {
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        URL url = new URL(BASEURL + "/sms");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // Sending an SMS requires authentication
        conn.setRequestProperty("user_key", authKeys[0]);
        conn.setRequestProperty("Session_key", authKeys[1]);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Content-type", "application/json");
        conn.setDoOutput(true);

        String payload = gson.toJson(sendSMS);

        OutputStream os = conn.getOutputStream();
        os.write(payload.getBytes());
        os.flush();

        if (conn.getResponseCode() != 201) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String response = "";
        String output;
        while ((output = br.readLine()) != null) {
            response += output;
        }
        conn.disconnect();

        SendSMSResponse responseObj = gson.fromJson(response, SendSMSResponse.class);

        return responseObj.isValid();
    }
}
Copy code
<?php

define("BASEURL", "http://app.gateway.smsend.it/API/v1.0/REST/");
define("MESSAGE_HIGH_QUALITY", "N");
define("MESSAGE_MEDIUM_QUALITY", "L");
define("MESSAGE_LOW_QUALITY", "LL");

/*
* Authenticates the user given it's username and password.
* Returns the pair user_key, Session_key
*/
function login($username, $password) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, BASEURL . 
        'login?username=' . $username . 
        '&password=' . $password);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    if ($info['http_code'] != 200) {
        return null;
    }

    return explode(";", $response);
}

/*
* Sends an SMS message
*/
function sendSMS($auth, $sendSMS) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, BASEURL . 'sms');
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-type: application/json',
        'user_key: ' . $auth[0],
        'Session_key: ' . $auth[1]
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($sendSMS));
    $response = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    if ($info['http_code'] != 201) {
        return null;
    }

    return json_decode($response);
}

$auth = login('username', 'password');

$smsSent = sendSMS($auth, array(
    "message" => "Hello world!",
    "message_type" => MESSAGE_HIGH_QUALITY,
    "returnCredits" => false,
    "recipient" => array("+349123456789"),
    "sender" => null,     // Place here a custom sender if desired
    "scheduled_delivery_time" => date('YmdHis', strtotime("+5 minutes")), // postpone by 5 minutes
));

if ($smsSent->result == "OK") {
    echo 'SMS sent!';
}

?>
Copy code
# pip install requests
import requests
import json
import sys
import datetime

BASEURL = "http://app.gateway.smsend.it/API/v1.0/REST/"

MESSAGE_HIGH_QUALITY = "N"
MESSAGE_MEDIUM_QUALITY = "L"
MESSAGE_LOW_QUALITY = "LL"

def json_serial(obj):
    """ JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, datetime.datetime):
        serial = obj.isoformat()
        return serial

    raise TypeError ("Type not serializable")

def login(username, password):
    """ Authenticates the user given it's username and password. """
    """ Returns a couple (user_key, session_key) """
    
    r = requests.get("%slogin?username=%s&password=%s"
        % (BASEURL, username, password))

    if r.status_code != 200:
        return None

    user_key, session_key = r.text.split(';')
    return user_key, session_key

def sendSMS(auth, sendsms):
    """Sends an SMS"""

    headers = { 'user_key': auth[0],

                'Session_key': auth[1],
                'Content-type' : 'application/json' }

    r = requests.post("%ssms" % BASEURL,
                      headers=headers,
                      data=json.dumps(sendsms, default=json_serial))

    if r.status_code != 201:
        return None

    return json.loads(r.text)


if __name__ == "__main__":
    auth = login("username", "password")

    if not auth:
        print("Unable to login..")
        sys.exit(-1)

    sentSMS = sendSMS(auth,
        {
          "message" : "Hello world!",
          "message_type" : MESSAGE_HIGH_QUALITY,
          "returnCredits" : False,
          "recipient": ["+349123456789",],

          # Place here a custom sender if desired
          "sender": None,

          # Postpone the SMS sending by 5 minutes
          "scheduled_delivery_time" : (datetime.datetime.now() +
                                       datetime.timedelta(minutes=5))
        })

    if sentSMS['result'] == "OK":
        print("SMS sent!")
Copy code
var BASEURL = 'http://app.gateway.smsend.it/API/v1.0/REST/';
var MESSAGE_HIGH_QUALITY = "N";
var MESSAGE_MEDIUM_QUALITY = "L";
var MESSAGE_LOW_QUALITY = "LL";
var request = require('request');

/*
* Authenticates the user given it's username and password.  Callback
* is called when completed. If error is false, then an authentication
* object is passed to the callback as second parameter.
*/
function login(username, password, callback) {
    request({
        url: BASEURL + 'login?username=' + username + '&password=' + password,
        method: 'GET',
        callback: function (error, responseMeta, response) {
            if (!error && responseMeta.statusCode == 200) {
                var auth = response.split(';');
                callback(error, {
                    user_key : auth[0],
                    session_key : auth[1]
                });
            }
            else {
                callback(error);
            }
        }
    });
}

/*
* Sends an SMS message
*/
function sendSMS(auth, sendsms, callback) {
    request({
        url: BASEURL + 'sms',
        method: 'POST',
        headers: { 'user_key' : auth.user_key, 'Session_key' : auth.session_key },
        json: true,
        body:  sendsms,

        callback: function (error, responseMeta, response) {
            if (!error && responseMeta.statusCode == 201) {
                callback(response.result !== 'OK', response);
            }
            else {
                callback(false);
            }
        }
    });
}

var smsData = {
    "returnCredits": true,
    "recipient": [
        "+393471234567",
        "+393471234568"
    ],
    "scheduled_delivery_time": "20171223101010",
    "message": "Hello world!",
    "message_type": MESSAGE_HIGH_QUALITY
}

login('username', 'password',
      function(error, auth) {
          if (!error) {
              sendSMS(auth, smsData,
                      function(error, data) {
                          if (error) {
                              console.log("An error occurred");
                          }
                          else {
                              console.log("SMS Sent!");
                          }
                      });
          }
    else {
              console.log("Unable to login");
          }
      });
Copy code
require 'net/http'
require 'uri'
require 'json'

BASEURL = "http://app.gateway.smsend.it/API/v1.0/REST/"

MESSAGE_HIGH_QUALITY = "N"
MESSAGE_MEDIUM_QUALITY = "L"
MESSAGE_LOW_QUALITY = "LL"

# Authenticates the user given it's username and password. Returns a
# couple (user_key, session_key)
def login(username, password)
  uri = URI.parse(BASEURL + "login?username=" + username  + "&password=" + password)

  # Create the HTTP objects
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(uri.request_uri)
  request['Content-type'] = 'application/json'

  # Send the request
  responseData = http.request(request)
  if responseData.code == "200"
    return responseData.body.split(';')
  end

  return None
end

# Sends an SMS
def sendSMS(auth, sendSMS)
  uri = URI.parse(BASEURL + "sms")

  # Create the HTTP objects
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri.request_uri)
  request['Content-type'] = 'application/json'
  request['user_key'] = auth[0]
  request['Session_key'] = auth[1]
  request.body = sendSMS.to_json

  # Send the request
  responseData = http.request(request)
  if responseData.code == "201"
    return JSON.parse(responseData.body)
  else
    return None
  end
end

####################
# Main

auth = login('username', 'password')

if not auth
  puts "Unable to login"
else
  response = sendSMS(auth,
     {
      "returnCredits": true,
      "recipient": [
                     "+393471234567",
                     "+393471234568"
                   ],
      "message": "Hello world!",
      "message_type": MESSAGE_HIGH_QUALITY,
     })
  if response['result'] == 'OK'
    puts "SMS Sent!"
  else
    puts "An error occurred"
  end
end
Copy code
using System;
using System.Text;
using System.Net;

// We are using JSON.NET (http://www.newtonsoft.com/json)
using Newtonsoft.Json;

/*
* The following code has been compiled and tested using the MONO project.
* To compile using MONO: mcs -r:Newtonsoft.Json.dll example.cs
*/
namespace RestApplication
{
    class Program
    {
        public static String BASEURL = "http://app.gateway.smsend.it/API/v1.0/REST/";
        public static String MESSAGE_HIGH_QUALITY = "N";
        public static String MESSAGE_MEDIUM_QUALITY = "L";
        public static String MESSAGE_LOW_QUALITY = "LL";

        static void Main(string[] args)
        {
            String[] auth = authenticate("username", "password");

            SendSMS sendSMSRequest = new SendSMS();

            sendSMSRequest.message = "Hello World!";
            sendSMSRequest.message_type = MESSAGE_HIGH_QUALITY;
            sendSMSRequest.recipient = new String[] {"+39349123456789"};

            // Send the SMS message at the given date (Optional)
            sendSMSRequest.scheduled_delivery_time = new DateTime(2017, 8, 18, 13, 31, 00);

            SMSSent smsSent = sendSMS(auth, sendSMSRequest);

            if ("OK".Equals(smsSent.result)) {
                Console.WriteLine("SMS successfully sent!");
            }
        }

        /*
        * Authenticates the user given it's username and
        * password. Returns a couple (user_key, session_key)
        */
        static String[] authenticate(String username, String password)
        {
            String[] auth = null;

            using (var wb = new WebClient())
            {
                var response = wb.DownloadString(BASEURL +
                     "login?username=" + username +
                     "&password=" + password);
                auth = response.Split(';');
            }
            return auth;
        }

        /*
        * Sends an SMS
        */
        static SMSSent sendSMS(String[] auth, SendSMS sendSMS)
        {
            using (var wb = new WebClient())
            {
                wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
                wb.Headers.Add("user_key", auth[0]);
                wb.Headers.Add("Session_key", auth[1]);

                String json = JsonConvert.SerializeObject(sendSMS);

                var sentSMSBody =
                    wb.UploadString(BASEURL + "sms", "POST", json);

                SMSSent sentSMSResponse =
                    JsonConvert.DeserializeObject<SMSSent>(sentSMSBody);

               return sentSMSResponse;
            }
        }
    }

    /*
    * This object is used to create an SMS message sending request.
    * The JSon object is then automatically created starting from an
    * instance of this class, using JSON.NET.
    */
    class SendSMS
    {
        // The message body
        public String message;

        // The message type
        public String message_type;

        // The sender Alias (TPOA)
        public String sender;

        // Postpone the SMS message sending to the specified date
        public DateTime? scheduled_delivery_time;

        // The list of recipients
        public String[] recipient;

        // Should the API return the remaining credits?
        public Boolean returnCredits = false;
    }


    /*
    * This class represents the API Response. It is automatically created starting
    * from the JSON object returned by the server, using GSon
    */
    class SMSSent
    {
        // The result of the SMS message sending
        public String result;

        // The order ID of the SMS message sending
        public String order_id;

        // The actual number of sent SMS messages
        public int total_sent;

        // The remaining credits
        public int remaining_credits;
    }

}
Copy code
#!/usr/bin/env perl

use warnings;
use strict;
use LWP::UserAgent;

# Install using Cpan: "cpan JSON"
use JSON;

use constant BASEURL => "http://app.gateway.smsend.it/API/v1.0/REST/";
use constant MESSAGE_HIGH_QUALITY => "N";
use constant MESSAGE_MEDIUM_QUALITY => "L";
use constant MESSAGE_LOW_QUALITY => "LL";

sub authenticate($$$) {
    my ($ua, $username, $password) = @_;

    my $server_endpoint = BASEURL . "login?username=$username&password=$password";

    my $req = HTTP::Request->new(GET => $server_endpoint);
    $req->header('Content-type' => 'application/json');

    my $resp = $ua->request($req);
    if ($resp->is_success && $resp->code == 200) {
        my $response = $resp->decoded_content;

        my ($user_key, $session_key) = $response =~ /(.*);(.*)/;

        return [$user_key, $session_key];
    }
}

sub send_sms($$$) {
    my ($ua, $auth, $sendsms) = @_;

    my $server_endpoint = BASEURL . "sms";

    my $req = HTTP::Request->new(POST => $server_endpoint);

    # IMPORTANT: Not adding the ':' before 'user_key' and
    # 'Session_key' will result in perl to automatically rewrite the
    # headers as 'User-Key' and 'Session-Key', which is not supported
    # by our API.
    $req->header('Content_type' => 'application/json',
                 ':user_key' => $auth->[0],
                 ':Session_key' => $auth->[1]);

    $req->content(to_json($sendsms));

    my $resp = $ua->request($req);
    if ($resp->is_success) {
        return from_json($resp->decoded_content);
    }
}

my $ua = LWP::UserAgent->new;

my $auth = authenticate($ua, "username", "password");

die ("Unable to authenticate\n") unless ($auth);

my $sendsms = {
    "message" => "Hello world!",
    "message_type" => MESSAGE_HIGH_QUALITY,
    "recipient" => ["+39349123456789"],
};

my $smssent = send_sms($ua, $auth, $sendsms);

print "SMS successfully sent!\n" if ($smssent->{"result"} eq "OK");