Code Examples
// Nuget dependencies at time of writing:
// RestSharp v106.6.10
// Newtonsoft.Json v12.0.3
// First we need to get some scaffolding out the way, we will need a httpClient to handle
// the communication with our endpoints.
// For the purpose of this guide we will make use of the RestSharp Nuget package as it is
// both easy to use and understand.
// as well as Newtonsoft.Json parser to more elegantly handle the responses.
// we point the client we will use at the SMSPortal REST URL.
var client = new RestClient("https://rest.smsportal.com");
// the authToken we will retrieve for this session.
var authToken = "";
// Before we can send an SMS via the RESTful API, we first need to retrieve an authToken.
// To do so, you need to prepare your API key and secret generated from the website in the
// manner our endpoint expects to find it. Namely: { key:secret }
var apiKey = "";
var apiSecret = "";
var accountApiCredentials = $"{apiKey}:{apiSecret}";
// Our endpoint expects this string to be Base64 encoded, to that end:
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(accountApiCredentials);
var base64Credentials = Convert.ToBase64String(plainTextBytes);
// We then need to call the authentication endpoint to generate the AuthToken we will be
// using for the rest of your interactions with our RESTful interface.
var authRequest = new RestRequest("/v1/Authentication", Method.GET);
// We need to set the Authorization header to contain our BASE64 encoded API credential
// and specify these credentials are in Basic format.
authRequest.AddHeader("Authorization", $"Basic {base64Credentials}");
// We then call the SMSPortal endpoint to authenticate and provide us with an AuthToken.
var authResponse = client.Execute(authRequest);
// We ensure we get a success response.
if (authResponse.StatusCode == HttpStatusCode.OK)
{
// We save the new JWT authToken, ready to use in our coming requests.
var authResponseBody = JObject.Parse(authResponse.Content);
// retreive the token field from the response
authToken = authResponseBody["token"].ToString();
// Be advised, we also provide the schema used to generate the token as well as the
// validity period of the token (24hr at the time of writing). For more advanced
// setups we advise using these fields to better ensure you do not experience downtime
// due to an expired or invalid token.
}
else
{
Console.WriteLine(authResponse.ErrorMessage);
return;
}
// Now on to the fun part. We prepare the next request as a POST to the /Bulkmessages endpoint.
var sendRequest = new RestRequest("/v1/bulkmessages", Method.POST);
// We can now populate the Authentication header with our new token.
var authHeader = $"Bearer {authToken}";
sendRequest.AddHeader("Authorization", $"{authHeader}");
// We next need to add a body containing the specifics of the send.
// this is just a basic SMS, have a look at our docs page to see what you can get up to.
sendRequest.AddJsonBody(new
{
Messages = new[]
{
new
{
content = "Hello SMS World",
destination = ">>Your test phone number<<"
}
}
});
// with everything prepared we fire off the Request.
var sendResponse = client.Execute(sendRequest);
// Again we ensure the response we get back indicates success.
if (sendResponse.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine(sendResponse.Content);
}
else
{
// If not, we can look to the error message to see what went
// wrong, be it a faulty auth token or improper formatting of the Request body.
Console.WriteLine(sendResponse.ErrorMessage);
}
//Dependency: com.squareup.okhttp:okhttp:2.7.5
//Dependency: com.squareup.okio:okio:1.13.0
OkHttpClient client = new com.squareup.okhttp.OkHttpClient();
RequestBody sendRequestBody = RequestBody.create(
com.squareup.okhttp.MediaType.parse("application/json; charset=utf-8"),
"{\n" +
" \"messages\": [\n" +
" {\n" +
" \"content\": \"" + "Hello SMS World" + "\",\n" +
" \"destination\": \"" + "12345678910" + "\"\n" +
" }\n" +
" ]\n" +
"}");
Request sendRequest = new com.squareup.okhttp.Request.Builder()
.url("https://rest.smsportal.com/v1/bulkmessages")
.header("Authorization", "Bearer [Your Authorization Token]")
.post(sendRequestBody)
.build();
try {
Response sendResponse = client.newCall(sendRequest).execute();
System.out.println(sendResponse.body().string());
}
catch (IOException e) {
System.out.println("Request failed. Exception: " + e.getMessage());
}
<?php
require 'C:\composer\vendor\autoload.php'; #Dependency: php composer.phar require guzzlehttp/guzzle
$client = new \GuzzleHttp\Client();
$currentTime = new \DateTime(null, new \DateTimeZone("UTC"));
$sendRequestBody = json_decode('{ "messages" : [ { "content" : "Hello SMS World", "destination" : "12345678910" } ] }',true);
$sendResponse = $client->request('POST', "https://rest.smsportal.com/v1/bulkmessages", [
'json' => $sendRequestBody,
'headers' => ['Authorization' => "Bearer your.authorization.token"],
'http_errors' => false
]);
if($sendResponse->getStatusCode() == 200){
echo 'Send Successful. Details:';
echo $sendResponse->getBody();
}
else {
echo 'Send Failed. Details:';
echo $sendResponse->getBody();
}
?>
import requests #Dependency: pip install requests
import datetime
sendRequest = {
"messages": [ {"content": "Hello SMS World", "destination": "12345678910"} ]
}
try:
sendResponse = requests.post("https://rest.smsportal.com/v1/bulkmessages",
headers={'Authorization': 'Bearer [Your Authorization Token]'},
json=sendRequest)
if sendResponse.status_code == 200:
print(sendResponse.json())
else:
print(sendResponse.json())
except Exception as e:
print(e)
require 'httparty' #Dependency: gem install httparty
require 'json'
sendRequestBody = JSON.generate({
"messages" => [ { "content" => "Hello SMS World", "destination" => "12345678910" } ]
})
sendResponse = HTTParty.post("https://rest.smsportal.com/v1/bulkmessages",
:headers => { 'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => "Bearer your.authorization.token"},
:body => sendRequestBody)
if sendResponse.code == 200
print 'Send Successful. Details:'
print sendResponse
else
print 'Send Failed. Details:'
print sendResponse
end
var request = require('request')
var sendRequest = {
'messages': [ {'content': "Hello SMS World", 'destination': "12345678910"} ]
};
request.post({
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer [Your Authorization Token]'},
url: 'https://rest.smsportal.com/v1/bulkmessages',
json: true,
body: sendRequest
}, function (error, response, body) {
console.log(body);
});
Updated 12 months ago
See also