Introduction To The Web API

SMSPrime exposes an HTTP Post Application Programming Interface (i.e. Web API) for corporate and premium users that lets you integrate short messaging services into your projects for multifarious applications including services like notification and reminder systems, confirmation systems, marketing and advertising systems etc.

A subset of the functionality already available in our client dashboard has been exposed as web methods to make it easy to automate certain tasks from within your applications and services.

Our Web API runs on top of HTTP, and can be implemented in most environments that support creating HTTP POST requests.

Activating The Web API

When a user is first registered on SMSPrime, an endpoint is created for that user that permits automatic method requests via the API.

However the endpoint is deactivated by default for security reasons and has to be enabled on a per user basis. To activate the Web API, login to your dashboard on http://smsprime.com/user/login/ with a valid account.

Navigate the menu to API -> Activate to get to the Web API section.

Generate a API Key to use for your requests, and then click on the Activate button.

Copy and save the key for later use.

The Web API URL

The primary SMSPrime URL for sending your requests varies for each client, but it usually goes in the template form:

https://smsprime.com/api.module/[username]/[datatype]

The parameters in square brackets can be any of:

  • username - The username of the client registered on SMPrime
  • datatype - The input and output data format. SMSPrime currently supports the use of the strings xml, and json

Consider a scenario for a client registered on SMPrime as userfoo, who wants to send an SMS to a client from his website.

A sample request to send an SMS message using XML would be posted to a URL that looks like this:

https://smsprime.com/api.module/userfoo/xml

Request and Response Data Structure and Formats

SMSPrime currently supports two platform independent mime formats (i.e. XML,JSON) for exchanging data via the Web API.

A request is essentially initiated by building a request block in your preferred mime format with the essential instructions.

Consider the generic synopsis of a request:

XML Request

<?xml version="1.0" encoding="utf-8"?> <Request> <header> [Header Data in XML format] </header> <body> [Body Data in XML format] </body> </Request>

Notice how the name of the root xml element is Request

JSON Request

The JSON variation would look something like this:

{ "Request" : { "header" : [ Header Data in JSON format... ], "body" : [ Body Data in JSON format... ] } }

Again, notice how the root element is named Request

The internal structure of the data block is similar, and interchangeable between these data formats. Which format you use depends on which one best suits your application and needs.

HTTP Responses are similarly built into the requested format and are wrapped up in Response tags or elements,as appropriate.

XML Response

<?xml version="1.0" encoding="utf-8"?> <Response> <statusText>...</statusText> <statusCode>..</statusCode> <auxillary> [ .................. ] </auxillary> </Response>

JSON Response

{ "Response" : { "statusText" : ..., "statusCode" : ... "auxillary" : { ... } } }

Authentication and Signature

The SMSPrime Web API is an authenticated service. Only registered users on the SMSPrime network can make requests via the API.

It is important to note that SMSPrime does not require you to authenticate the request with your password in clear text. Each request is made to a per-user URL, and the mime data must contain a head section which carries the signature of the user. The signature is obtained from an md5 hash of the concatenation of the user's API Key and username.

The signature of the user can be generated thus in language agnostic terms:

signature = md5Hash ( username + API Key)

The plus operator in that illustration merely indicates a concatenation of the two string fields (i.e. the username, and the API Key).

Hence the head block of the request would be built thus in XML:

<Request> <head> <auth> <signature>d3ee7457b04ac808071df590caa8c856</signature> </auth> </head> [ .................. ] </Request>

Where the signature is the md5 hash of the concatenation of the username and key generated from your console at SMSPrime.

Web API Service Methods

Web methods are the ways by which tasks are executed on the Web API. Each request must specify a method as a unit of execution within a request via the API. Based on the specific method, parameters may be needed to further define the context in which the method must run.

A sample template request with a method and parameters is as follows:

<?xml version="1.0" encoding="utf-8"?> <Request> <header> [Header Data in XML format] </header> <body> <method>method-name</method> <parameters> <param1>flash</param1> <param2>flash</param2> [ ....... more parameters ..... ] <paramN>flash</paramN> </parameters> </body> </Request>

The following methods are supported:

Send Method

The send method directs the platform to send an SMS on your behalf. It works with the following parameters:

Parameter Parameter Specification Parameter Options Sample
type Type of message to send default,flash flash
destination A comma separated list of mobile recipients. Take care to format these recipients in their international formats A valid MSISDN 2348034853921
source Your sender id A maximum of 11 characters for alpahnumeric names and 16 for numbers Mr Sender
header A header for binary and concatenated messages, optional A valid UDH  
shortmessage The SMS message A string that must be a maximum of 160 characters  
group The name of a group or list that exists on SMSPrime, optional A valid group name group one

A sample request block would go as follows:

<?xml version="1.0" encoding="utf-8"?> <Request> <header> <auth> <signature>d3ee7457b04ac808071df590caa8c856</signature> </auth> </header> <body> <auxillary> <balance>1</balance> </auxillary> <method>send</method> <parameters> <type>default</type> <destination>2348044563398</destination> <source>WebAPI Trxs</source> <header>optional header</header> <shortmessage>The SMS content will be here</shortmessage> <group>optional group name</group> </parameters> </body> </Request>

This request also includes an auxillary instruction that requests the user's balance after the operation. A sample response from the server would go something like:

<?xml version="1.0" encoding="UTF-8"?> <Response> <statusCode>200</statusCode> <statusText>Request Succeeded</statusText> <auxillary> <balance>253.5</balance> </auxillary> </Response>

Balance Method

An outright balance method directs the platform to return the user's current balance. It has no parameters.

A balance request looks like this:

<?xml version="1.0" encoding="utf-8"?> <Request> <header> <auth> <signature>d3ee7457b04ac808071df590caa8c856</signature> </auth> </header> <body> <method>balance</method> </body> </Request>

A sample response look like this:

<?xml version="1.0" encoding="UTF-8"?> <Response> <statusCode>200</statusCode> <statusText>Request Succeeded</statusText> <auxillary> <balance>253.5</balance> </auxillary> </Response>

Standard Error Codes

SMSPrime supports the following error codes on the API

Code Description
200 Request succeeded
300 Unknown error
301 Authentication failure
302 Acess denied
303 Request is empty or invalid. No data found
304 Request data is not well formed
305 Request method is not allowed
306 Your request was not processed
307 No method was indicated or invalid method
399 399 features a range of platform specific error codes varied by context

Examples

This section features some examples in specific languages. For all intent and purposes, we will assume the following:

username : johnsmith
API Key : 84212BF54BD90A6B42B0E96B88E5AEE3
data format : XML

Derivate API URL : https://smsprime.com/api.module/johnsmith/xml

PHP SAMPLE

<pre> <?php /** Sample API request to SMSPrime using XML **/ //username $username = "johnsmith"; //API Key $APIKey = "84212BF54BD90A6B42B0E96B88E5AEE3"; //Mime mode $dataformat = "xml"; //Derivative URL $APIUrl = "https://smsprime.com/api.module/$username/$dataformat"; //Compute a signature for the user by concatenating the username and the api key $signature = md5($username . $APIKey); //Build an xml request for method send, with an auxillary instruction to get the balance $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?> <Request> <header> <auth> <signature>$signature</signature> </auth> </header> <body> <auxillary> <balance>1</balance> </auxillary> <method>send</method> <parameters> <type>default</type> <destination>2348044563398</destination> <source>WebAPI Trxs</source> <header>optional header</header> <shortmessage>The SMS content will be here</shortmessage> <group>optional group name</group> </parameters> </body> </Request>"; //Use CURL to post //You could as well easily use fsockopen and its family of functions $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $APIUrl ); curl_setopt($ch, CURLOPT_POST, 1 ); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $postResult = curl_exec($ch); if (curl_errno($ch)) { print curl_error($ch); } curl_close($ch); print htmlentities("$postResult");

C# SAMPLE

//This sample uses the .NET Framework using System; using System.Text; using System.Net; using System.IO; /// <summary> /// Sample API request to SMSPrime using XML /// </summary> class WebAPIRequest { public static void Main(string[] args) { //username String username = "johnsmith"; //API Key String APIKey = "84212BF54BD90A6B42B0E96B88E5AEE3"; //Mime mode String dataformat = "xml"; //Derivative URL String APIUrl = "https://smsprime.com/api.module/" + username + "/" + dataformat; //Compute a signature for the user by concatenating the username and the api key String signature = md5( username + APIKey); //Build an xml request for method send, with an auxillary instruction to get the balance String xml = @"<?xml version='1.0' encoding='utf-8'?> <Request> <header> <auth> <signature>" + signature + @"</signature> </auth> </header> <body> <auxillary> <balance>1</balance> </auxillary> <method>send</method> <parameters> <type>default</type> <destination>2348044563398</destination> <source>WebAPI Trxs</source> <header>optional header</header> <shortmessage>The SMS content will be here</shortmessage> <group>optional group name</group> </parameters> </body> </Request>"; //Post the data String response = HttpPost(APIUrl, xml); Console.WriteLine(response); Console.ReadKey(); } public static String md5(String operand) { // step 1, calculate MD5 hash from operand System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(operand); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return sb.ToString(); } public static String HttpPost(string uri, string data) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; byte[] bytes = Encoding.ASCII.GetBytes(data); Stream os = null; try { // send the Post request.ContentLength = bytes.Length; //Count bytes to send os = request.GetRequestStream(); os.Write(bytes, 0, bytes.Length); //Send it } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (os != null) { os.Close(); } } try { // get the response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response == null) { return null; } StreamReader sr = new StreamReader(response.GetResponseStream()); return sr.ReadToEnd().Trim(); } catch (Exception ex) { Console.WriteLine(ex.Message); } return null; } }

JAVA SAMPLE

/** * * @file WebAPIRequest.java * @date May 2, 2010 */ package SMSPrime; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.net.URL; import java.net.URLConnection; import java.security.MessageDigest; /** * Sample API request to SMSPrime using XML * @author TripodWire Ltd. * */ public class WebAPIRequest { /** * @param args */ public static void main(String[] args) { //username String username = "johnsmith"; //API Key String APIKey = "84212BF54BD90A6B42B0E96B88E5AEE3"; //Mime mode String dataformat = "xml"; //Derivative URL String APIUrl = "https://smsprime.com/api.module/" + username + "/" + dataformat; //Compute a signature for the user by concatenating the username and the api key String signature = md5( username + APIKey); //Build an xml request for method send, with an auxillary instruction to get the balance String xml = "<?xml version='1.0' encoding='utf-8'?>" + "<Request>" + "<header>" + "<auth>" + "<signature>" + signature + "</signature>" + "</auth>" + "</header>" + "<body>" + "<auxillary>" + "<balance>1</balance>" + "</auxillary>" + "<method>send</method>" + "<parameters>" + "<type>default</type>" + "<destination>2348044563398</destination>" + "<source>WebAPI Trxs</source>" + "<header>optional header</header>" + "<shortmessage>The SMS content will be here</shortmessage>" + "<group>optional group name</group>" + "</parameters>" + "</body>" + "</Request>"; //Post the data String response = HttpPost(APIUrl, xml); System.out.println(response); } /** * Calculate the md5 hash of a string * @param operand * @return String */ public static String md5 (String operand) { String hash = null; try{ byte[] inputBytes = operand.getBytes("UTF-8"); MessageDigest mdFive = MessageDigest.getInstance("MD5"); byte[] digestBytes = mdFive.digest(inputBytes); BigInteger big = new BigInteger(1,digestBytes); String hashString = big.toString(16); //Pad the string if length is less that 32 chars while(hashString.length() < 32){ hashString = "0" + hashString; } hash = hashString; } catch (Exception e) { System.out.println(e.getMessage()); } return hash; } /** * Do an HTTP Post and return the response * @param uri * @param data * @return String */ public static String HttpPost(String uri,String data) { String stringResponse = ""; try { URL url = new URL(uri); URLConnection conn = url.openConnection(); // Set connection parameters. conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); // Make server believe we are form data... conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); // Write out the bytes of the content string to the stream. out.writeBytes(data); out.flush(); out.close(); // Read response from the input stream. BufferedReader in = new BufferedReader(new InputStreamReader(conn .getInputStream())); String temp; while ((temp = in.readLine()) != null) { stringResponse += temp + "\n"; } temp = null; in.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return stringResponse; } }

PYTHON SAMPLE

#!/usr/bin/env python # -*- coding: UTF-8 -*- # enable debugging import cgitb import md5 import urllib import urllib2 cgitb.enable() print "Content-Type: text/plain;charset=utf-8" print # replace with your username username = "username" apiKey = "84212BF54BD90A6B42B0E96B88E5AEE3" # you can get the api URL from your web api console when logged in # however you can also derive it by doing something like this: dataformat = "xml" apiURL = "https://smsprime.com/api.module/" + username + "/" + dataformat + "/" signature = md5.new( username + apiKey ).hexdigest() apiRequest = """<?xml version="1.0" encoding="utf-8"?> <Request> <header> <auth> <signature>""" + signature + """</signature> </auth> </header> <body> <method>send</method> <parameters> <type>default</type> <destination>2348044563398</destination> <source>Web API Trx</source> <shortmessage>Content served over the HTTP API</shortmessage> </parameters> </body> </Request>""" # send the apiRequest via a standard HTTP request request = urllib2.Request( apiURL , apiRequest ) response = urllib2.urlopen( request ) html = response.read() # print out the results print html
 

Copyright © 2009 Tripodwire Ltd. All rights reserved. | Full Site