Textanywhere Rest API - Introduction
Welcome to the Textanywhere API documentation!
The API is divided into subsections, which are briefly described below. For details about each section, please refer to the respective section.
Quick start: full examples: This section contains code examples that are ready to be copied and pasted in your favorite editor or IDE, and are ready to be executed! Just type in your registration email and password and you’re ready to go.
Authentication: This section describes how to authenticate requests to the Textanywhere API. All API methods require authentication.
User: The following are utility functions regarding the authenticated user (e.g. the user status, password reset, etc)
Contacts: This part of the API is used to manage contacts.
Contact groups: This section describes how groups of contacts are created, updated and deleted. SMS messages can be directly sent to groups of contacts.
Sending SMS messages: This is the part of the API that allows to send SMS messages, to single recipients, saved contacts or groups of contacts.
SMS messages history: Used to retrieve the SMS messages sending history.
SMS Blacklist / Stop SMS: This section allow to insert and to retrieve the list of SMS blacklist / Stop SMS.
Subaccounting: If enabled as a superaccount, the user can create subaccounts that can be assigned to third-parties. Superaccounts may or may not share credits with their subaccounts.
Receiving SMS messages: The methods described in this section are used to retrieve the received SMS messages.
Two Factor authentication: This API provides the Two Factor Authentication via SMS.
Quick start: full examples
Send an SMS message: full example
echo 'Full example not available for shell'
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 = "https://api.textanywhere.com/API/v1.0/REST/";
public static final String MESSAGE_HIGH_QUALITY = "GP";
public static final String MESSAGE_MEDIUM_QUALITY = "GS";
public static void main(String[] args) {
try {
String[] authKeys = login("UserParam{my_registration_email}", "UserParam{my_password}");
SendSMSRequest sendSMS = new SendSMSRequest();
sendSMS.setMessage("Hello world!");
sendSMS.setMessageType(MESSAGE_HIGH_QUALITY);
sendSMS.addRecipient("+44123456789");
// 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();
}
}
<?php
define("BASEURL", "https://api.textanywhere.com/API/v1.0/REST/");
define("MESSAGE_HIGH_QUALITY", "GP");
define("MESSAGE_MEDIUM_QUALITY", "GS");
/**
* 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('UserParam{my_registration_email}', 'UserParam{my_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('YmdHi', strtotime("+5 minutes")), // postpone by 5 minutes
));
if ($smsSent->result == "OK") {
echo 'SMS sent!';
}
?>
# pip install requests
import requests
import json
import sys
import datetime
BASEURL = "https://api.textanywhere.com/API/v1.0/REST/"
MESSAGE_HIGH_QUALITY = "GP"
MESSAGE_MEDIUM_QUALITY = "GS"
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("UserParam{my_registration_email}", "UserParam{my_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!")
var BASEURL = 'https://api.textanywhere.com/API/v1.0/REST/';
var MESSAGE_HIGH_QUALITY = "GP";
var MESSAGE_MEDIUM_QUALITY = "GS";
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": [
"+443471234567",
"+443471234568"
],
"scheduled_delivery_time": "20171223101010",
"message": "Hello world!",
"message_type": MESSAGE_HIGH_QUALITY
}
login('UserParam{my_registration_email}', 'UserParam{my_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");
}
});
require 'net/http'
require 'uri'
require 'json'
BASEURL = "https://api.textanywhere.com/API/v1.0/REST/"
MESSAGE_HIGH_QUALITY = "GP"
MESSAGE_MEDIUM_QUALITY = "GS"
# 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('UserParam{my_registration_email}', 'UserParam{my_password}')
if not auth
puts "Unable to login"
else
response = sendSMS(auth,
{
"returnCredits": true,
"recipient": [
"+443471234567",
"+443471234568"
],
"message": "Hello world!",
"message_type": MESSAGE_HIGH_QUALITY,
})
if response['result'] == 'OK'
puts "SMS Sent!"
else
puts "An error occurred"
end
end
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
{
public class Program
{
public static String BASEURL = "https://api.textanywhere.com/API/v1.0/REST/";
public static String MESSAGE_HIGH_QUALITY = "GP";
public static String MESSAGE_MEDIUM_QUALITY = "GS";
public static void Main(string[] args)
{
String[] auth = authenticate("UserParam{my_registration_email}", "UserParam{my_password}");
SendSMS sendSMSRequest = new SendSMS();
sendSMSRequest.message = "Hello World!";
sendSMSRequest.message_type = MESSAGE_HIGH_QUALITY;
sendSMSRequest.recipient = new String[] {"+44349123456789"};
// 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())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
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;
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use LWP::UserAgent;
use constant BASEURL => "https://api.textanywhere.com/API/v1.0/REST/";
use constant MESSAGE_HIGH_QUALITY => "GP";
use constant MESSAGE_MEDIUM_QUALITY => "GS";
sub authenticate($$$) {
my ($ua, $username, $password) = @_;
$username = uri_escape($username);
$password = uri_escape($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, "UserParam{my_registration_email}", "UserParam{my_password}");
die ("Unable to authenticate\n") unless ($auth);
my $sendsms = {
"message" => "Hello world!",
"message_type" => MESSAGE_HIGH_QUALITY,
"recipient" => ["+44349123456789"],
};
my $smssent = send_sms($ua, $auth, $sendsms);
print "SMS successfully sent!\n" if ($smssent->{"result"} eq "OK");
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 UserParam{my_registration_email}
and UserParam{my_password}
strings, add a valid
recipient list and execute the code!
The listed example authenticates the user using registration email and password with the Authentication API and then sends an SMS calling the Send SMS API.
Authentication API
Authentication methods
The following are the two available methods to authenticate a user, given the registration email and a password (registration required):
Using a temporary session key, which expires after a certain amount of time has passed with no performed API calls with that key.
Using an authentication token, which does not expire, except when an account is deactivated or suspended.
In both cases, the returned user_key, as well as the session key or the token, are required to be provided in the HTTP request headers in order to perform any API call after the login.
Authenticate using a session key
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/login' -H 'Content-Type: application/json' \
-H 'Authorization: Basic base64_encode(UserParam{my_registration_email}:UserParam{my_password})'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/login' -H 'Content-Type: application/json' \
-H 'Authorization: Basic base64_encode(UserParam{my_registration_email}:UserParam{my_password})'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/login", auth = HTTPBasicAuth('UserParam{my_registration_email}', 'UserParam{my_password}'))
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
user_key, session_key = response.split(';')
print("user_key: " + user_key)
print("Session_key: " + session_key)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/login");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Encode username and password as Basic Authentication standard
String encoding = Base64.getEncoder().encodeToString(("UserParam{my_registration_email}:UserParam{my_password}").getBytes(‌"UTF‌​-8"));
conn.setRequestProperty("Authorization", "Basic " + encoding);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
String[] parts = response.split(";");
String user_key = parts[0];
String session_key = parts[1];
System.out.println("user_key: " + user_key);
System.out.println("Session_key: " + session_key);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/login');
curl_setopt($ch, CURLOPT_USERPWD, 'UserParam{my_registration_email}:UserParam{my_password}');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$values = explode(";", $response);
echo('user_key: ' . $values[0]);
echo('Session_key: ' . $values[1]);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/login',
method: 'GET',
headers: { 'auth' : 'UserParam{my_registration_email}:UserParam{my_password}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
var arr = response.split(';');
console.log("user_key: " + arr[0]);
console.log("Session_key: " + arr[1]);
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/login")
# 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'
request.basic_auth 'UserParam{my_registration_email}', 'UserParam{my_password}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
user_key, session_key = response.split(';')
puts "user_key: " + user_key
puts "Session_key: " + session_key
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("UTF-8")
.GetBytes(UserParam{my_registration_email} + ":" + UserParam{my_password}));
wb.Headers.Add("Authorization", "Basic " + encoded);
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/login");
String[] auth = response.Split(';');
Console.WriteLine("user_key: " + auth[0]);
Console.WriteLine("Session_key: " + auth[1]);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/login";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
$req->authorization_basic(':my_registration_email', ':my_password');
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my ($user_key, $session_key) = $response =~ /(.*);(.*)/;
print "user_key: $user_key\n";
print "Session_key: $session_key\n";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
USER_KEY;SESSION_KEY
Where USER_KEY is the user key and SESSION_KEY is the session key
The login with session key API lets you authenticate by using your REGISTRATION_EMAIL and API password (that can be configured in your account setting page), and returns a token to be used for authenticating the next API calls. The following HTTP headers should be provided after the login:
user_key:UserParam{USER_KEY}
Session_key:UserParam{SESSION_KEY}
Where UserParam{USER_KEY}
and UserParam{SESSION_KEY}
are the values returned by the
login API.
HTTP request
GET /API/v1.0/REST/login
Authentication
We use Authorization header with Basic Authentication standard.
"Authorization: Basic {base64_encode(registration_email:password)}"
Returns
Code | Description |
---|---|
200 | The user_key and the session_key |
401 | [Unauthorized] Credentials are incorrect |
400 | Other errors, details are in the body |
Authenticate using a user token
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/token' -H 'Content-Type: application/json' \
-H 'Authorization: Basic base64_encode(UserParam{my_registration_email}:UserParam{my_password})'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/token' -H 'Content-Type: application/json' \
-H 'Authorization: Basic base64_encode(UserParam{my_registration_email}:UserParam{my_password})'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/token", auth = HTTPBasicAuth('UserParam{my_registration_email}', 'UserParam{my_password}'))
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
user_key, access_token = response.split(';')
print("user_key: " + user_key)
print("Access_token: " + access_token)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/token");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Encode username and password as Basic Authentication standard
String encoding = Base64.getEncoder().encodeToString(("UserParam{my_registration_email}:UserParam{my_password}").getBytes(‌"UTF‌​-8"));
conn.setRequestProperty("Authorization", "Basic " + encoding);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
String[] parts = response.split(";");
String user_key = parts[0];
String access_token = parts[1];
System.out.println("user_key: " + user_key);
System.out.println("Access_token: " + access_token);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/token');
curl_setopt($ch, CURLOPT_USERPWD, 'UserParam{my_registration_email}:UserParam{my_password}');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$values = explode(";", $response);
echo('user_key: ' . $values[0]);
echo('Access_token: ' . $values[1]);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/token',
method: 'GET',
headers: { 'auth' : 'UserParam{my_registration_email}:UserParam{my_password}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
var arr = response.split(';');
console.log("user_key: " + arr[0]);
console.log("Access_token: " + arr[1]);
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/token")
# 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'
request.basic_auth 'UserParam{my_registration_email}', 'UserParam{my_password}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
user_key, access_token = response.split(';')
puts "user_key: " + user_key
puts "Access_token: " + access_token
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("UTF-8")
.GetBytes(UserParam{my_registration_email} + ":" + UserParam{my_password}));
wb.Headers.Add("Authorization", "Basic " + encoded);
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/token");
String[] auth = response.Split(';');
Console.WriteLine("user_key: " + auth[0]);
Console.WriteLine("Access_token: " + auth[1]);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/token";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
$req->authorization_basic(':my_registration_email', ':my_password');
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my ($user_key, $access_token) = $response =~ /(.*);(.*)/;
print "user_key: $user_key\n";
print "Access_token: $access_token\n";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
USER_KEY;ACCESS_TOKEN
Where USER_KEY is the user key and ACCESS_TOKEN is the access token
The login with token API lets you authenticate by using your REGISTRATION_EMAIL and API password, and returns a token to be used for authenticating the next API calls. The following HTTP headers should be provided after the login:
user_key:UserParam{USER_KEY}
Access_token:UserParam{ACCESS_TOKEN}
Where UserParam{USER_KEY}
and UserParam{ACCESS_TOKEN}
are the values returned by the
login API.
HTTP request
GET /API/v1.0/REST/token
Authentication
We use Authorization header with Basic Authentication standard.
"Authorization: Basic {base64_encode(registration_email:password)}"
Returns
Code | Description |
---|---|
200 | The user_key and the access token |
401 | [Unauthorized] Credentials are incorrect |
400 | Other errors, details are in the body |
User API
The following are utility functions regarding the Authenticated User (e.g. the user status, password reset, etc)
Dashboard
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/dashboard' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/dashboard' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/dashboard", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
print(response)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/dashboard");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
System.out.println(response);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/dashboard');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo($response);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/dashboard',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log(response);
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/dashboard")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts response
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/dashboard");
Console.WriteLine(response);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/dashboard";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
https://api.textanywhere.com/API/v1.0/REST//s/user/external-auth?k=07366A25DF70038A22B9D284AB13E856BD95C6227&action=FC07AD201AE372F378&action-params=7010AB
API used to retrieve the dashboard URL of the authenticated user
HTTP request
GET /API/v1.0/REST/dashboard
Returns
Code | Description |
---|---|
200 | Returns the URL for the user’s dashboard |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
400 | Other errors, details are in the body |
Verify session
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/checksession' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/checksession' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/checksession", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
print("Is session valid: " + str(response == "true"))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/checksession");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
System.out.println("Is session valid: " + ("true".equals(response)));
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/checksession');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Is session valid: ' . ($response === "true"));
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/checksession',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Is session valid: ' + (response == "true"));
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/checksession")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Is session valid " + response
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/checksession");
Console.WriteLine("Is session valid: " + response);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/checksession";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
"true" or "false"
Checks whether the user session is still active and valid (without renewal).
HTTP request
GET /API/v1.0/REST/checksession
Returns
Code | Description |
---|---|
200 | String “true” if the session is valid, “false” otherwise. |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
400 | Other errors, details are in the body |
Reset WebApp password
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="UserParam{new_password}"' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="UserParam{new_password}"' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="UserParam{new_password}"", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
print("Password changed: " + str(response == "true"))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="UserParam{new_password}"");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
System.out.println("Password changed: " + ("true".equals(response)));
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="UserParam{new_password}"');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Password changed: ' . ($response === "true"));
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="UserParam{new_password}"',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Password changed: ' + (response == "true"));
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="UserParam{new_password}"")
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Password changed " + response
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="UserParam{new_password}"", "POST", null);
Console.WriteLine("Password changed: " + response);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/pwdreset?password=".uri_escape(""UserParam{new_password}"")."";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
json "true" or "false"
Changes the password to authenticate the user via WebApp
HTTP request
POST /API/v1.0/REST/pwdreset
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
password | String | The new user password | Yes | - |
Returns
Code | Description |
---|---|
200 | String “true” on success, “false” otherwise |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] User key does not exist |
Reset API password
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/pwdreset/api' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"password": "UserParam{new_password}"
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/pwdreset/api' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"password": "UserParam{new_password}"
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"password": "UserParam{new_password}"
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/pwdreset/api", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
print("Password changed: " + str(response == "true"))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/pwdreset/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"password\": \"UserParam{new_password}\"" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
System.out.println("Password changed: " + ("true".equals(response)));
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "password": "UserParam{new_password}"' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/pwdreset/api');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Password changed: ' . ($response === "true"));
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/pwdreset/api',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"password": "UserParam{new_password}"
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Password changed: ' + (response == "true"));
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/pwdreset/api")
payload = {
"password": "UserParam{new_password}"
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Password changed " + response
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"password\": \"UserParam{new_password}\"" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/pwdreset/api", "POST", payload);
Console.WriteLine("Password changed: " + response);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/pwdreset/api";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"password" => "UserParam{new_password}"
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
json "true" or "false"
Changes the password to authenticate the user via API
HTTP request
POST /API/v1.0/REST/pwdreset/api/
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
password | String | The new user password | Yes | - |
Returns
Code | Description |
---|---|
200 | String “true” on success, “false” otherwise |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] User key does not exist |
SMS Credits and email service status
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/status' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/status' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/status", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/status");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/status');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/status',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/status")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/status");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/status";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"money": null,
"sms": [
{
"type": "GS",
"quantity": 11815
},
{
"type": "GP",
"quantity": 10407
},
{
"type": "EE",
"quantity": 10387
}
],
"email": {
"bandwidth": 2000.0,
"purchased": "2015-01-16",
"billing": "EMAILPERHOUR",
"expiry": "2016-01-17"
}
}
Used to retrieve the SMS Credits and email service status of the user identified by the id.
HTTP request
GET /API/v1.0/REST/status?getMoney=UserParam{value}&typeAliases=UserParam{value}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
getMoney | String “true” or “false” | Add user current money to response | No | “false” |
typeAliases | String “true” or “false” | Returns the actual names for the message types instead of the internal ID. This is not done by default only because of retrocompatibility issues. | No, but suggested | “false” |
Returns
Code | Description |
---|---|
200 | A Json object representing the user SMS Credits and email service status |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] Credentials are incorrect |
Contacts API
This part of the API is used to manage contacts.
Add a contact
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/contact' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}",
"gender": "UserParam{GENDER}",
"fax": "UserParam{FAX}",
"zip": "UserParam{ZIP}",
"address": "UserParam{ADDRESS}",
"city": "UserParam{CITY}",
"province": "UserParam{PROVINCE}",
"birthdate": "UserParam{BIRTHDATE}",
"groupIds": [
"UserParam{GRP1}",
"UserParam{GRP2}"
]
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/contact' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}",
"gender": "UserParam{GENDER}",
"fax": "UserParam{FAX}",
"zip": "UserParam{ZIP}",
"address": "UserParam{ADDRESS}",
"city": "UserParam{CITY}",
"province": "UserParam{PROVINCE}",
"birthdate": "UserParam{BIRTHDATE}",
"groupIds": [
"UserParam{GRP1}",
"UserParam{GRP2}"
]
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}",
"gender": "UserParam{GENDER}",
"fax": "UserParam{FAX}",
"zip": "UserParam{ZIP}",
"address": "UserParam{ADDRESS}",
"city": "UserParam{CITY}",
"province": "UserParam{PROVINCE}",
"birthdate": "UserParam{BIRTHDATE}",
"groupIds": [
"UserParam{GRP1}",
"UserParam{GRP2}"
]
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/contact", headers=headers, data=payload)
if r.status_code != 201:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/contact");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"email\": \"UserParam{EMAIL}\", " +
" \"phoneNumber\": \"UserParam{PHONENUMBER}\", " +
" \"name\": \"UserParam{NAME}\", " +
" \"surname\": \"UserParam{SURNAME}\", " +
" \"gender\": \"UserParam{GENDER}\", " +
" \"fax\": \"UserParam{FAX}\", " +
" \"zip\": \"UserParam{ZIP}\", " +
" \"address\": \"UserParam{ADDRESS}\", " +
" \"city\": \"UserParam{CITY}\", " +
" \"province\": \"UserParam{PROVINCE}\", " +
" \"birthdate\": \"UserParam{BIRTHDATE}\", " +
" \"groupIds\": [" +
" \"UserParam{GRP1}\", " +
" \"UserParam{GRP2}\"" +
" ]" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 201) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "email": "UserParam{EMAIL}", ' .
' "phoneNumber": "UserParam{PHONENUMBER}", ' .
' "name": "UserParam{NAME}", ' .
' "surname": "UserParam{SURNAME}", ' .
' "gender": "UserParam{GENDER}", ' .
' "fax": "UserParam{FAX}", ' .
' "zip": "UserParam{ZIP}", ' .
' "address": "UserParam{ADDRESS}", ' .
' "city": "UserParam{CITY}", ' .
' "province": "UserParam{PROVINCE}", ' .
' "birthdate": "UserParam{BIRTHDATE}", ' .
' "groupIds": [' .
' "UserParam{GRP1}", ' .
' "UserParam{GRP2}"' .
' ]' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/contact');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 201) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/contact',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}",
"gender": "UserParam{GENDER}",
"fax": "UserParam{FAX}",
"zip": "UserParam{ZIP}",
"address": "UserParam{ADDRESS}",
"city": "UserParam{CITY}",
"province": "UserParam{PROVINCE}",
"birthdate": "UserParam{BIRTHDATE}",
"groupIds": [
"UserParam{GRP1}",
"UserParam{GRP2}"
]
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 201) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact")
payload = {
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}",
"gender": "UserParam{GENDER}",
"fax": "UserParam{FAX}",
"zip": "UserParam{ZIP}",
"address": "UserParam{ADDRESS}",
"city": "UserParam{CITY}",
"province": "UserParam{PROVINCE}",
"birthdate": "UserParam{BIRTHDATE}",
"groupIds": [
"UserParam{GRP1}",
"UserParam{GRP2}"
]
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "201"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"email\": \"UserParam{EMAIL}\", " +
" \"phoneNumber\": \"UserParam{PHONENUMBER}\", " +
" \"name\": \"UserParam{NAME}\", " +
" \"surname\": \"UserParam{SURNAME}\", " +
" \"gender\": \"UserParam{GENDER}\", " +
" \"fax\": \"UserParam{FAX}\", " +
" \"zip\": \"UserParam{ZIP}\", " +
" \"address\": \"UserParam{ADDRESS}\", " +
" \"city\": \"UserParam{CITY}\", " +
" \"province\": \"UserParam{PROVINCE}\", " +
" \"birthdate\": \"UserParam{BIRTHDATE}\", " +
" \"groupIds\": [" +
" \"UserParam{GRP1}\", " +
" \"UserParam{GRP2}\"" +
" ]" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/contact", "POST", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/contact";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"email" => "UserParam{EMAIL}",
"phoneNumber" => "UserParam{PHONENUMBER}",
"name" => "UserParam{NAME}",
"surname" => "UserParam{SURNAME}",
"gender" => "UserParam{GENDER}",
"fax" => "UserParam{FAX}",
"zip" => "UserParam{ZIP}",
"address" => "UserParam{ADDRESS}",
"city" => "UserParam{CITY}",
"province" => "UserParam{PROVINCE}",
"birthdate" => "UserParam{BIRTHDATE}",
"groupIds" => [
"UserParam{GRP1}",
"UserParam{GRP2}"
]
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 201) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
# The HTTP location header that points to the created contact:
'Location': '/contact/AVvZEwZHHnl8wUZve6CT'
Add a contact to the user’s addressbook.
HTTP request
POST /API/v1.0/REST/contact
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
String (a valid email) | The email of the contact | Yes | - | |
phoneNumber | String (a non empty string) | The phone number of the contact. The phone number numbers must be in the international format (+443471234567 or 00443471234567) | Yes | “” |
name | String (max 256 chars) | The first name of the contact | No | “” |
surname | String (max 256 chars) | The last name of the contact | No | “” |
gender | String (“m” or “f”) | The gender of the contact | No | “” |
fax | String (max 32 chars) | The Fax number of the contact | No | “” |
address | String (max 256 chars) | The address of the contact | No | “” |
city | String (max 32 chars) | The city of the contact | No | “” |
province | String (max 32 chars) | The province of the contact | No | “” |
birthdate | String [ddMMyy, yyyyMMdd, ddMMyyHHmm, yyyyMMddHHmmss, yyyy-MM-dd HH:mm, yyyy-MM-dd HH:mm.0] | The birth date of the contact | No | “” |
promotiondate | String [ddMMyy, yyyyMMdd, ddMMyyHHmm, yyyyMMddHHmmss, yyyy-MM-dd HH:mm, yyyy-MM-dd HH:mm.0] | An additional date field | No | “” |
rememberdate | String [ddMMyy, yyyyMMdd, ddMMyyHHmm, yyyyMMddHHmmss, yyyy-MM-dd HH:mm, yyyy-MM-dd HH:mm.0] | An additional date field | No | “” |
zip | String (max 16 chars) | The ZIP code of the contact | No | “” |
groupIds | List(String) | The groups (Ids) in which the contact will be added | No | [] |
custom1 | String | Custom field 1 | No | “” |
custom2 | String | Custom field 2 | No | “” |
custom3 | String | Custom field 3 | No | “” |
custom4 | String | Custom field 4 | No | “” |
custom5 | String | Custom field 5 | No | “” |
custom6 | String | Custom field 6 | No | “” |
custom7 | String | Custom field 7 | No | “” |
custom8 | String | Custom field 8 | No | “” |
custom9 | String | Custom field 9 | No | “” |
custom10 | String | Custom field 10 | No | “” |
Returns
Code | Description |
---|---|
201 | Empty string, and the HTTP location header containing the path of the newly created contact |
400 | campaign not active or not found, no email provided, group not owned or a generic error. Details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Add multiple contacts
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/contacts' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"contacts": [
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}"
},
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}"
}
],
"updateExistingContact": true
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/contacts' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"contacts": [
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}"
},
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}"
}
],
"updateExistingContact": true
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"contacts": [
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}"
},
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}"
}
],
"updateExistingContact": true
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/contacts", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/contacts");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"contacts\": [" +
" {" +
" \"email\": \"UserParam{EMAIL}\", " +
" \"phoneNumber\": \"UserParam{PHONENUMBER}\", " +
" \"name\": \"UserParam{NAME}\", " +
" \"surname\": \"UserParam{SURNAME}\"" +
" }, " +
" {" +
" \"email\": \"UserParam{EMAIL}\", " +
" \"phoneNumber\": \"UserParam{PHONENUMBER}\", " +
" \"name\": \"UserParam{NAME}\", " +
" \"surname\": \"UserParam{SURNAME}\"" +
" }" +
" ], " +
" \"updateExistingContact\": true" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "contacts": [' .
' {' .
' "email": "UserParam{EMAIL}", ' .
' "phoneNumber": "UserParam{PHONENUMBER}", ' .
' "name": "UserParam{NAME}", ' .
' "surname": "UserParam{SURNAME}"' .
' }, ' .
' {' .
' "email": "UserParam{EMAIL}", ' .
' "phoneNumber": "UserParam{PHONENUMBER}", ' .
' "name": "UserParam{NAME}", ' .
' "surname": "UserParam{SURNAME}"' .
' }' .
' ], ' .
' "updateExistingContact": true' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/contacts');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/contacts',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"contacts": [
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}"
},
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}"
}
],
"updateExistingContact": true
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/contacts")
payload = {
"contacts": [
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}"
},
{
"email": "UserParam{EMAIL}",
"phoneNumber": "UserParam{PHONENUMBER}",
"name": "UserParam{NAME}",
"surname": "UserParam{SURNAME}"
}
],
"updateExistingContact": true
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"contacts\": [" +
" {" +
" \"email\": \"UserParam{EMAIL}\", " +
" \"phoneNumber\": \"UserParam{PHONENUMBER}\", " +
" \"name\": \"UserParam{NAME}\", " +
" \"surname\": \"UserParam{SURNAME}\"" +
" }, " +
" {" +
" \"email\": \"UserParam{EMAIL}\", " +
" \"phoneNumber\": \"UserParam{PHONENUMBER}\", " +
" \"name\": \"UserParam{NAME}\", " +
" \"surname\": \"UserParam{SURNAME}\"" +
" }" +
" ], " +
" \"updateExistingContact\": true" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/contacts", "POST", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/contacts";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"contacts" => [
{
"email" => "UserParam{EMAIL}",
"phoneNumber" => "UserParam{PHONENUMBER}",
"name" => "UserParam{NAME}",
"surname" => "UserParam{SURNAME}"
},
{
"email" => "UserParam{EMAIL}",
"phoneNumber" => "UserParam{PHONENUMBER}",
"name" => "UserParam{NAME}",
"surname" => "UserParam{SURNAME}"
}
],
"updateExistingContact" => true
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
2
Add multiple contacts to the user’s addressbook.
HTTP request
POST /API/v1.0/REST/contacts
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
contacts | Json array of Contacts | Array of Json object, formatted as ADD a contact | Yes | “” |
updateExistingContact | boolean | True to update existing contacts in case of clash, false to drop and insert them | No | false |
keepExistingGroupsAndCampaigns | boolean | True to keep all old contact groups associations and campaigns subscription | No | false |
Returns
Code | Description |
---|---|
200 | Number of contacts correctly created |
400 | campaign not active or not found, no email provided, group not owned or a generic error. Details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get a contact
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/contact/UserParam{contact_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/contact/UserParam{contact_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/contact/UserParam{contact_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/contact/UserParam{contact_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/contact/UserParam{contact_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/contact/UserParam{contact_id}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact/UserParam{contact_id}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/contact/UserParam{contact_id}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/contact/UserParam{contact_id}";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"email":"mario.rossi@gmail.com",
"phoneNumber":"+44349123456789",
"name": "Mario",
"surname": "Rossi",
"groupIds":[ ],
"gender":"m",
"fax":null,
"address":null,
"city":null,
"province":null,
"birthdate":"1966-05-11",
"zip":null
}
Get a contact’s details
HTTP request
GET /API/v1.0/REST/contact/UserParam{contact_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
CONTACT_ID | String | The contact ID | Yes | - |
Returns
Code | Description |
---|---|
200 | The contact’s details |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The given CONTACT_ID was not found |
Get all contacts
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/contact' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/contact' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/contact", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/contact");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/contact');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/contact',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/contact");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/contact";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
[
{
"email":"mario.rossi@gmail.com",
"phoneNumber":"+44349123456789",
"name": "Mario",
"surname": "Rossi",
"groupIds":[ ],
"gender":"m",
"fax":null,
"address":null,
"city":null,
"province":null,
"birthdate":"1966-05-11",
"zip":null
},
{
"email":"giuseppe.bianchi@gmail.com",
"phoneNumber":"+44349123456789",
"name": "Giuseppe",
"surname": "Bianchi",
"groupIds":[ ],
"gender":"m",
"fax":null,
"address":null,
"city":null,
"province":null,
"birthdate":"1978-03-22",
"zip":null
}
]
Get the contact’s details full list.
HTTP request
GET /API/v1.0/REST/contact
Returns
Code | Description |
---|---|
200 | The contacts’ details list |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The given CONTACT_ID was not found |
List contact’s custom fields
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/contacts/fields' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/contacts/fields' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/contacts/fields", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/contacts/fields");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/contacts/fields');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/contacts/fields',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/contacts/fields")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/contacts/fields");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/contacts/fields";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
[
{
"idField": "{CUSTOM_KEY}",
"placeholder": "%{PLACEHOLDER_NAME}%",
"label": "{LABEL_OR_KEY_TO_BE_DISPLAYED}",
"dataType": "{STRING|INTEGER|DATE|EMAIL|BOOLEAN}"
}
]
Returns the list of custom contact fields for the user
HTTP request
GET /API/v1.0/REST/contacts/fields
Returns
Code | Description |
---|---|
200 | Successful request |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
Add contact to SMS blacklist
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/UserParam{contact_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/UserParam{contact_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/UserParam{contact_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/UserParam{contact_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/UserParam{contact_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/UserParam{contact_id}',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/UserParam{contact_id}")
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/UserParam{contact_id}", "POST", null);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/UserParam{contact_id}";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
true
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
CONTACT_ID | String | The id of the contact that will be added | Yes | - |
Returns the result of operation
HTTP request
POST /API/v1.0/REST/contact/add_to_blacklist/UserParam{contact_id}
Returns
Code | Description |
---|---|
200 | Successful request |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | Contact not found |
Add multiple contacts to sms blacklist
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
[
"AV3vrSlPuGYfQz6BgjeI",
"BVvrSlPuGYfQz6BgjeI"
]
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
[
"AV3vrSlPuGYfQz6BgjeI",
"BVvrSlPuGYfQz6BgjeI"
]
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """[
"AV3vrSlPuGYfQz6BgjeI",
"BVvrSlPuGYfQz6BgjeI"
]"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "[" +
" \"AV3vrSlPuGYfQz6BgjeI\", " +
" \"BVvrSlPuGYfQz6BgjeI\"" +
"]";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '[' .
' "AV3vrSlPuGYfQz6BgjeI", ' .
' "BVvrSlPuGYfQz6BgjeI"' .
']';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: [
"AV3vrSlPuGYfQz6BgjeI",
"BVvrSlPuGYfQz6BgjeI"
],
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch")
payload = [
"AV3vrSlPuGYfQz6BgjeI",
"BVvrSlPuGYfQz6BgjeI"
]
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "[" +
" \"AV3vrSlPuGYfQz6BgjeI\", " +
" \"BVvrSlPuGYfQz6BgjeI\"" +
"]";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch", "POST", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = [
"AV3vrSlPuGYfQz6BgjeI",
"BVvrSlPuGYfQz6BgjeI"
];
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
2
Add multiple contacts to the user’s blacklist.
HTTP request
POST /API/v1.0/REST/contact/add_to_blacklist_batch
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
— | List(String) | Array of contact ids | Yes | “” |
Returns
Code | Description |
---|---|
200 | Number of contacts correctly put in the blacklist |
400 | Some of the contactsId specified were wrong |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Add phone number to sms blacklist
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=UserParam{phone_number}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=UserParam{phone_number}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=UserParam{phone_number}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=UserParam{phone_number}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=UserParam{phone_number}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=UserParam{phone_number}',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=UserParam{phone_number}")
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=UserParam{phone_number}", "POST", null);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=".uri_escape("UserParam{phone_number}")."";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
true
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
phoneNumber | String | The phone number that will be added to blacklist | Yes | - |
Returns the result of operation
HTTP request
POST /API/v1.0/REST/contact/add_to_blacklist?phoneNumber=UserParam{phone_number}
Returns
Code | Description |
---|---|
200 | Successful request |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
Contacts groups API
This section describes how groups of contacts are created, updated and deleted. SMS messages can be directly sent to groups of contacts.
Create a contacts group
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/group' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"name": "UserParam{NAME}",
"description": "UserParam{DESCRIPTION}"
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/group' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"name": "UserParam{NAME}",
"description": "UserParam{DESCRIPTION}"
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"name": "UserParam{NAME}",
"description": "UserParam{DESCRIPTION}"
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/group", headers=headers, data=payload)
if r.status_code != 201:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/group");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"name\": \"UserParam{NAME}\", " +
" \"description\": \"UserParam{DESCRIPTION}\"" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 201) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "name": "UserParam{NAME}", ' .
' "description": "UserParam{DESCRIPTION}"' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/group');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 201) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/group',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"name": "UserParam{NAME}",
"description": "UserParam{DESCRIPTION}"
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 201) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/group")
payload = {
"name": "UserParam{NAME}",
"description": "UserParam{DESCRIPTION}"
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "201"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"name\": \"UserParam{NAME}\", " +
" \"description\": \"UserParam{DESCRIPTION}\"" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/group", "POST", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/group";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"name" => "UserParam{NAME}",
"description" => "UserParam{DESCRIPTION}"
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 201) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
# The HTTP location header that points to the created group:
'Location': '/group/{group_id}'
Creates an empty group of contacts given a name and a description.
HTTP request
POST /API/v1.0/REST/group
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
name | String | The name of the group | Yes | - |
description | String | The description of the group | Yes | - |
Returns
Code | Description |
---|---|
201 | An empty string, and the HTTP location header containing the path to the newly created group |
400 | If the group name is invalid, or other errors, with a code error |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] If the requesting user does not exist. |
Modify an existing contacts group
# Session Key example
curl -XPUT 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"name": "UserParam{NAME}",
"description": "UserParam{DESCRIPTION}"
}
'
# Access token example
curl -XPUT 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"name": "UserParam{NAME}",
"description": "UserParam{DESCRIPTION}"
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"name": "UserParam{NAME}",
"description": "UserParam{DESCRIPTION}"
}"""
r = requests.put("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("PUT");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"name\": \"UserParam{NAME}\", " +
" \"description\": \"UserParam{DESCRIPTION}\"" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "name": "UserParam{NAME}", ' .
' "description": "UserParam{DESCRIPTION}"' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}',
method: 'PUT',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"name": "UserParam{NAME}",
"description": "UserParam{DESCRIPTION}"
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}")
payload = {
"name": "UserParam{NAME}",
"description": "UserParam{DESCRIPTION}"
}
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Put.new(uri.request_uri)
request['Content-type'] = 'application/json'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"name\": \"UserParam{NAME}\", " +
" \"description\": \"UserParam{DESCRIPTION}\"" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}", "PUT", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}";
my $req = HTTP::Request->new(PUT => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"name" => "UserParam{NAME}",
"description" => "UserParam{DESCRIPTION}"
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
# The HTTP location header that points to the modified group:
'Location': '/group/{group_id}'
Updates a given contacts group
HTTP request
PUT /API/v1.0/REST/group/UserParam{group_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
name | String | The name of the group | Yes | - |
description | String | The description of the group | Yes | - |
Returns
Code | Description |
---|---|
200 | An empty string, and the HTTP location header containing the path to the updated group |
400 | If the given group_id is invalid, if the address book is locked, if the group name is invalid, or other errors, with a code error |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] If the requesting user does not exist. |
Delete a contacts group
# Session Key example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{groupid}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{groupid}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.delete("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{groupid}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{groupid}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("DELETE");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{groupid}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{groupid}',
method: 'DELETE',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{groupid}")
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Delete.new(uri.request_uri)
request['Content-type'] = 'application/json'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{groupid}", "DELETE", new NameValueCollection());
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/group/UserParam{groupid}";
my $req = HTTP::Request->new(DELETE => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
""
Deletes the contacts group identified by the given ID.
HTTP request
DELETE /API/v1.0/REST/group/UserParam{group_id}?deletecontacts=UserParam{del}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
group_id | String | The group ID to be deleted | Yes | - |
deletecontacts | String “true” or “false” | If “true”, also deletes all contacts in the group | No | “false” |
Returns
Code | Description |
---|---|
200 | An empty string |
400 | If the given group_id is invalid, if the address book is locked, if the group name is invalid, or other errors, with a code error |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] Credentials are incorrect |
List contact groups
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/groups' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/groups' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/groups", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/groups");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/groups');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/groups',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/groups")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/groups");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/groups";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"groups":[ "// The list of groups"
{
"id_group": (string), "// The ID of a group in the list"
"group_name": (string), "// The group name"
"group_description": (string) "// The group description"
},
{...} "// Other groups in the list (omitted..)"
],
"pageNumber": (int), "// Paging: The page number"
"pageSize": (int), "// Paging: The page size"
"Total": (int) "// Paging: The total number of groups"
}
Returns the list of existing contact groups, paginated.
HTTP request
GET /API/v1.0/REST/groups?pageNumber=UserParam{page}&pageSize=UserParam{size}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
pageNumber | int | The page number | No | 1 |
pageSize | int | The page size | No | 5 |
Returns
Code | Description |
---|---|
200 | The paginated list of contact groups, as a Json object |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Add a contact to a group
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}")
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}", "POST", null);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
# The HTTP location header that points to the contact:
'Location': '/contact/UserParam{contact_id}'
Adds the specified contact in the specified contacts group.
HTTP request
POST /API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
group_id | String | The contact group ID | Yes | - |
contact_id | String | The contact ID | Yes | - |
Returns
Code | Description |
---|---|
200 | An empty string, and the HTTP location header containing the URL of the contact |
400 | If contact_id is invalid, if the addressbook is locked or other. Details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Remove a contact from a group
# Session Key example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.delete("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("DELETE");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}',
method: 'DELETE',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}")
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Delete.new(uri.request_uri)
request['Content-type'] = 'application/json'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}", "DELETE", new NameValueCollection());
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}";
my $req = HTTP::Request->new(DELETE => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
# The HTTP location header that points to the contact:
'Location': '/contact/{contact_id}'
Removes the specified contact from the specified contacts group.
HTTP request
DELETE /API/v1.0/REST/group/UserParam{group_id}/contact/UserParam{contact_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
group_id | String | The contact Group ID | Yes | - |
contact_id | String | The contact ID | Yes | - |
Returns
Code | Description |
---|---|
200 | An empty string, and the HTTP location header containing the URL of the contact |
400 | If contact_id is invalid, if the addressbook is locked or other. Details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
SMS send API
This is the part of the API that allows to send SMS messages, to single recipients, saved contacts or groups of contacts.
Send an SMS message
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/sms' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello world!",
"recipient": [
"+443471234567",
"+443471234568"
],
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/sms' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello world!",
"recipient": [
"+443471234567",
"+443471234568"
],
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello world!",
"recipient": [
"+443471234567",
"+443471234568"
],
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/sms", headers=headers, data=payload)
if r.status_code != 201:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/sms");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"message_type\": \"UserParam{MESSAGE_TYPE}\", " +
" \"message\": \"Hello world!\", " +
" \"recipient\": [" +
" \"+443471234567\", " +
" \"+443471234568\"" +
" ], " +
" \"sender\": \"MySender\", " +
" \"scheduled_delivery_time\": \"20161223101010\", " +
" \"order_id\": \"123456789\", " +
" \"returnCredits\": true" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 201) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "message_type": "UserParam{MESSAGE_TYPE}", ' .
' "message": "Hello world!", ' .
' "recipient": [' .
' "+443471234567", ' .
' "+443471234568"' .
' ], ' .
' "sender": "MySender", ' .
' "scheduled_delivery_time": "20161223101010", ' .
' "order_id": "123456789", ' .
' "returnCredits": true' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/sms');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 201) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/sms',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello world!",
"recipient": [
"+443471234567",
"+443471234568"
],
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 201) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/sms")
payload = {
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello world!",
"recipient": [
"+443471234567",
"+443471234568"
],
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "201"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"message_type\": \"UserParam{MESSAGE_TYPE}\", " +
" \"message\": \"Hello world!\", " +
" \"recipient\": [" +
" \"+443471234567\", " +
" \"+443471234568\"" +
" ], " +
" \"sender\": \"MySender\", " +
" \"scheduled_delivery_time\": \"20161223101010\", " +
" \"order_id\": \"123456789\", " +
" \"returnCredits\": true" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/sms", "POST", payload);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/sms";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"message_type" => "UserParam{MESSAGE_TYPE}",
"message" => "Hello world!",
"recipient" => [
"+443471234567",
"+443471234568"
],
"sender" => "MySender",
"scheduled_delivery_time" => "20161223101010",
"order_id" => "123456789",
"returnCredits" => true
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 201) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result" : "OK", "//OK or errors"
"order_id" : "123456789",
"total_sent" : 2 "//SMS sent or credits used"
}
Sends an SMS message to a given list of recipients.
Landing Pages URLs
It is possible to include a link to a published Landing Page by
specifying the id_landing
parameter and by adding the following
placeholder in the message body: %PAGESLINK____________%
.
Landing pages must be first created and published in your user
panel, since you will need id_landing
to send it.
A list of published landing pages can be retrieved by using the Landing Pages APIs
SMS Link Analytics
When including URLs in the message, it may be convenient to use our SMS Link Analytics short URLs service to limit the number of characters used in the SMS message and having statistic on clic.
Our API can automatically generate a short link starting from a long one, and add it in the message.
To use this feature, use the %RICHURL________%
placeholder in the message body, that will be replaced with the generated short link, and the respective richsms_url parameter, that should be set to a valid URL.
Sender Alias
Alphanumeric aliases are required to be registered first, and need to be approved both from Us and AGCOM.
Aliases can be used only with high-quality message types.
HTTP request
POST /API/v1.0/REST/sms
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
message_type | String (“GP” for Gold+) | The type of SMS. | Yes | - |
message | String (max 1000 chars with “gsm” encoding, 450 with “ucs2” encoding) | The body of the message. *Message max length could be 160 chars when using low-quality SMSs. New line char needs to be codified as “\n”. | Yes | - |
recipient | List(String) | A list of recipents phone numbers. The recipients’ numbers must be in the international format (+443471234567 or 00443471234567) | Yes | - |
sender | String | The Sender name. If the message type allows a custom TPOA and the field is left empty, the user’s preferred TPOA is used. Must be empty if the message type does not allow a custom TPOA | No | “” |
scheduled_delivery_time | String [ddMMyy, yyyyMMdd, ddMMyyHHmm, yyyyMMddHHmmss, yyyy-MM-dd HH:mm, yyyy-MM-dd HH:mm.0] | The messages will be sent at the given scheduled time | No | null |
scheduled_delivery_timezone | Timezone(IANA time zone) | Optional timezone applied to scheduled_delivery_time date |
No | - |
order_id | String (max 32 chars, accepts only any letters, numbers, underscore, dot and dash) | Specifies a custom order ID | No | Generated UUID |
returnCredits | Bool | Returns the number of used sms credits. Note that it can be greater than sent SMS number: i.e. when message is more than 160 chars long, each SMS will consume more than one credit according to its length | No | “false” |
returnRemaining | Bool | Returns the number of remaining SMS credits for the quality used in the sent SMS and for the default user nation | No | false |
allowInvalidRecipients | Bool | Sending to an invalid recipient does not block the operation | No | false |
encoding | String (“gsm” or “ucs2”) | The SMS encoding. Use UCS2 for non standard character sets | No | “gsm” |
id_landing | int | The id of the published page. Also add the %PAGESLINK____________% placeholder in the message body |
No | - |
campaign_name | String | The campaign name | No | - |
max_fragments | int | The number of maximum fragments allowed per sms | No | Configured by user in settings page, Default 7 |
truncate | Bool | True, truncates any message exceeding max_fragments, False doesn’t send any overly long sms | No | Configured by user in settings page, Default true |
validity_period_min | int | Period after which the SMS message will be deleted from the SMS center. Please note the set expiry time may not be honoured by some mobile networks. | No | - |
richsms_url | String | The url where the rich url redirects. Also add the %RICHURL________% placeholder in the message body |
No | - |
Returns
Code | Description |
---|---|
201 | SMSs have been scheduled for delivery. |
400 | Invalid input. Details are in the response body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Send a parametric SMS message
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/paramsms' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello ${name}, welcome to ${nation}",
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true,
"allowInvalidRecipients": false,
"returnRemaining": true,
"recipients": {
"0": {
"recipient": "+443471234567",
"name": "Mark",
"nation": "Germany"
},
"1": {
"recipient": "+443477654321",
"name": "John",
"nation": "Alabama"
}
}
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/paramsms' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello ${name}, welcome to ${nation}",
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true,
"allowInvalidRecipients": false,
"returnRemaining": true,
"recipients": {
"0": {
"recipient": "+443471234567",
"name": "Mark",
"nation": "Germany"
},
"1": {
"recipient": "+443477654321",
"name": "John",
"nation": "Alabama"
}
}
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello ${name}, welcome to ${nation}",
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true,
"allowInvalidRecipients": false,
"returnRemaining": true,
"recipients": {
"0": {
"recipient": "+443471234567",
"name": "Mark",
"nation": "Germany"
},
"1": {
"recipient": "+443477654321",
"name": "John",
"nation": "Alabama"
}
}
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/paramsms", headers=headers, data=payload)
if r.status_code != 201:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/paramsms");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"message_type\": \"UserParam{MESSAGE_TYPE}\", " +
" \"message\": \"Hello ${name}, welcome to ${nation}\", " +
" \"sender\": \"MySender\", " +
" \"scheduled_delivery_time\": \"20161223101010\", " +
" \"order_id\": \"123456789\", " +
" \"returnCredits\": true, " +
" \"allowInvalidRecipients\": false, " +
" \"returnRemaining\": true, " +
" \"recipients\": {" +
" \"0\": {" +
" \"recipient\": \"+443471234567\", " +
" \"name\": \"Mark\", " +
" \"nation\": \"Germany\"" +
" }, " +
" \"1\": {" +
" \"recipient\": \"+443477654321\", " +
" \"name\": \"John\", " +
" \"nation\": \"Alabama\"" +
" }" +
" }" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 201) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "message_type": "UserParam{MESSAGE_TYPE}", ' .
' "message": "Hello ${name}, welcome to ${nation}", ' .
' "sender": "MySender", ' .
' "scheduled_delivery_time": "20161223101010", ' .
' "order_id": "123456789", ' .
' "returnCredits": true, ' .
' "allowInvalidRecipients": false, ' .
' "returnRemaining": true, ' .
' "recipients": {' .
' "0": {' .
' "recipient": "+443471234567", ' .
' "name": "Mark", ' .
' "nation": "Germany"' .
' }, ' .
' "1": {' .
' "recipient": "+443477654321", ' .
' "name": "John", ' .
' "nation": "Alabama"' .
' }' .
' }' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/paramsms');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 201) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/paramsms',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello ${name}, welcome to ${nation}",
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true,
"allowInvalidRecipients": false,
"returnRemaining": true,
"recipients": {
"0": {
"recipient": "+443471234567",
"name": "Mark",
"nation": "Germany"
},
"1": {
"recipient": "+443477654321",
"name": "John",
"nation": "Alabama"
}
}
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 201) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/paramsms")
payload = {
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello ${name}, welcome to ${nation}",
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true,
"allowInvalidRecipients": false,
"returnRemaining": true,
"recipients": {
"0": {
"recipient": "+443471234567",
"name": "Mark",
"nation": "Germany"
},
"1": {
"recipient": "+443477654321",
"name": "John",
"nation": "Alabama"
}
}
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "201"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"message_type\": \"UserParam{MESSAGE_TYPE}\", " +
" \"message\": \"Hello ${name}, welcome to ${nation}\", " +
" \"sender\": \"MySender\", " +
" \"scheduled_delivery_time\": \"20161223101010\", " +
" \"order_id\": \"123456789\", " +
" \"returnCredits\": true, " +
" \"allowInvalidRecipients\": false, " +
" \"returnRemaining\": true, " +
" \"recipients\": {" +
" \"0\": {" +
" \"recipient\": \"+443471234567\", " +
" \"name\": \"Mark\", " +
" \"nation\": \"Germany\"" +
" }, " +
" \"1\": {" +
" \"recipient\": \"+443477654321\", " +
" \"name\": \"John\", " +
" \"nation\": \"Alabama\"" +
" }" +
" }" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/paramsms", "POST", payload);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/paramsms";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"message_type" => "UserParam{MESSAGE_TYPE}",
"message" => "Hello ${name}, welcome to ${nation}",
"sender" => "MySender",
"scheduled_delivery_time" => "20161223101010",
"order_id" => "123456789",
"returnCredits" => true,
"allowInvalidRecipients" => false,
"returnRemaining" => true,
"recipients" => {
"0" => {
"recipient" => "+443471234567",
"name" => "Mark",
"nation" => "Germany"
},
"1" => {
"recipient" => "+443477654321",
"name" => "John",
"nation" => "Alabama"
}
}
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 201) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result" : "OK", "//OK or errors"
"order_id" : "123456789",
"total_sent" : 2 "//SMS sent or credits used"
}
Sends a parametric SMS message to a given list of recipients. With this API it is possible to put placeholders in the message body, and then, for each recipient, specify the values that will replace the placeholders in the message body, for that particular recipient message.
Placeholders are in the form ${ParameterName}
Landing Pages URLs
It is possible to include a link to a published Landing Page by
specifying the id_landing
parameter and by adding the following
placeholder in the message body: %PAGESLINK____________%
.
Landing pages must be first created and published in your user
panel, since you will need id_landing
to send it.
A list of published landing pages can be retrieved by using the Landing Pages APIs
SMS Link Analytics
When including URLs in the message, it may be convenient to use our SMS Link Analytics short URLs service to limit the number of characters used in the SMS message and having statistic on clic.
Our API can automatically generate a short link starting from a long one, and add it in the message.
To use this feature, use the %RICHURL________%
placeholder in the message body and set the parameter rich_mode
with one of following values:
DIRECT_URL
: in this case you must add the parameter richsms_url
with the url that you want to be shortened
RECIPIENT
: in this case the url must be set in the url
property for each recipient
in recipients
parameter.
You could omit richsms_mode
if you specify both the richsms_url
params and %RICHURL________%
placeholder.
Stashed changes
Sender Alias
Alphanumeric aliases are required to be registered first, and need to be approved both from Us and AGCOM.
Aliases can be used only with high-quality message types.
HTTP request
POST /API/v1.0/REST/paramsms
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
message_type | String (“GP” for Gold+) | The type of SMS. | Yes | - |
message | String (max 1000 chars with “gsm” encoding, 450 with “ucs2” encoding) | The body of the message. *Message max length could be 160 chars when using low-quality SMSs | Yes | - |
recipients | Map(String, Map(String, String)) | A map of recipents and relative parameters. The recipients’ numbers must be in the international format (+443471234567 or 00443471234567) | Yes | - |
sender | String | The Sender name. If the message type allows a custom TPOA and the field is left empty, the user’s preferred TPOA is used. Must be empty if the message type does not allow a custom TPOA | No | “” |
scheduled_delivery_time | String [ddMMyy, yyyyMMdd, ddMMyyHHmm, yyyyMMddHHmmss, yyyy-MM-dd HH:mm, yyyy-MM-dd HH:mm.0] | The messages will be sent at the given scheduled time | No | null |
scheduled_delivery_timezone | Timezone(IANA time zone) | Optional timezone applied to scheduled_delivery_time date |
No | - |
order_id | String (max 32 chars, accepts only any letters, numbers, underscore, dot and dash) | Specifies a custom order ID | No | Generated UUID |
returnCredits | Bool | Returns the number of credits used instead of the number of messages. i.e. when message is more than 160 chars long more than one credit is used | No | false |
returnRemaining | Bool | Returs the number of remaining SMSs | No | false |
allowInvalidRecipients | Bool | Sending to an invalid recipient does not block the operation | No | false |
encoding | String (“gsm” or “ucs2”) | The SMS encoding. Use UCS2 for non standard character sets | No | “gsm” |
id_landing | int | The id of the published page. Also add the %PAGESLINK____________% placeholder in the message body |
No | - |
campaign_name | String | The campaign name | No | - |
max_fragments | int | The number of maximum fragments allowed per sms | No | Configured by user in settings page, Default 7 |
truncate | Bool | True, truncates any message exceeding max_fragments, False doesn’t send any overly long sms | No | Configured by user in settings page, Default true |
validity_period_min | int | Period after which the SMS message will be deleted from the SMS center. Please note the set expiry time may not be honoured by some mobile networks. | No | - |
richsms_url | String | The url where the rich url redirects. Also add the %RICHURL________% placeholder in the message body |
No | - |
richsms_mode | String | Possible values are: DIRECT_URL : use when richsms_url is set at campaign level, the same for all recipient RECIPIENT : use in combination with url set in recipient. |
No | - |
Returns
Code | Description |
---|---|
200 | SMS have been successfully sent. The order ID and some other information is returned |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Send an SMS message to a group
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/smstogroups' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello world!",
"recipientsGroupdIds": [
"idGroup1",
"idGroup2"
],
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/smstogroups' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello world!",
"recipientsGroupdIds": [
"idGroup1",
"idGroup2"
],
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello world!",
"recipientsGroupdIds": [
"idGroup1",
"idGroup2"
],
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/smstogroups", headers=headers, data=payload)
if r.status_code != 201:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/smstogroups");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"message_type\": \"UserParam{MESSAGE_TYPE}\", " +
" \"message\": \"Hello world!\", " +
" \"recipientsGroupdIds\": [" +
" \"idGroup1\", " +
" \"idGroup2\"" +
" ], " +
" \"sender\": \"MySender\", " +
" \"scheduled_delivery_time\": \"20161223101010\", " +
" \"order_id\": \"123456789\", " +
" \"returnCredits\": true" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 201) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "message_type": "UserParam{MESSAGE_TYPE}", ' .
' "message": "Hello world!", ' .
' "recipientsGroupdIds": [' .
' "idGroup1", ' .
' "idGroup2"' .
' ], ' .
' "sender": "MySender", ' .
' "scheduled_delivery_time": "20161223101010", ' .
' "order_id": "123456789", ' .
' "returnCredits": true' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/smstogroups');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 201) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/smstogroups',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello world!",
"recipientsGroupdIds": [
"idGroup1",
"idGroup2"
],
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 201) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/smstogroups")
payload = {
"message_type": "UserParam{MESSAGE_TYPE}",
"message": "Hello world!",
"recipientsGroupdIds": [
"idGroup1",
"idGroup2"
],
"sender": "MySender",
"scheduled_delivery_time": "20161223101010",
"order_id": "123456789",
"returnCredits": true
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "201"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"message_type\": \"UserParam{MESSAGE_TYPE}\", " +
" \"message\": \"Hello world!\", " +
" \"recipientsGroupdIds\": [" +
" \"idGroup1\", " +
" \"idGroup2\"" +
" ], " +
" \"sender\": \"MySender\", " +
" \"scheduled_delivery_time\": \"20161223101010\", " +
" \"order_id\": \"123456789\", " +
" \"returnCredits\": true" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/smstogroups", "POST", payload);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/smstogroups";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"message_type" => "UserParam{MESSAGE_TYPE}",
"message" => "Hello world!",
"recipientsGroupdIds" => [
"idGroup1",
"idGroup2"
],
"sender" => "MySender",
"scheduled_delivery_time" => "20161223101010",
"order_id" => "123456789",
"returnCredits" => true
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 201) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result" : "OK", "//OK or errors"
"order_id" : "123456789",
"total_sent" : 2 "//SMS sent or credits used"
}
Send an SMS message to a set of contact groups.
Landing Pages URLs
It is possible to include a link to a published Landing Page by
specifying the id_landing
parameter and by adding the following
placeholder in the message body: %PAGESLINK____________%
.
Landing pages must be first created and published in your user
panel, since you will need id_landing
to send it.
A list of published landing pages can be retrieved by using the Landing Pages APIs
SMS Link Analytics
When including URLs in the message, it may be convenient to use our SMS Link Analytics short URLs service to limit the number of characters used in the SMS message and having statistic on clic.
Our API can automatically generate a short link starting from a long one, and add it in the message.
To use this feature, use the %RICHURL________%
placeholder in the message body, that will be replaced with the generated short link, and the respective richsms_url parameter, that should be set to a valid URL.
Sender Alias
Alphanumeric aliases are required to be registered first, and need to be approved both from Us and AGCOM.
Aliases can be used only with high-quality message types.
HTTP request
POST /API/v1.0/REST/smstogroups
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
message_type | String (“GP” for Gold+) | The type of SMS. | Yes | - |
message | String (max 1000 chars with “gsm” encoding, 450 with “ucs2” encoding) | The body of the message. *Message max length could be 160 chars when using low-quality SMSs | Yes | - |
recipientsGroupdIds | List(String) | A list of contact group ids. The recipients’ numbers must be in the international format (+443471234567 or 00443471234567) | Yes | - |
sender | String | The Sender name. If the message type allows a custom TPOA and the field is left empty, the user’s preferred TPOA is used. Must be empty if the message type does not allow a custom TPOA | No | “” |
scheduled_delivery_time | String [ddMMyy, yyyyMMdd, ddMMyyHHmm, yyyyMMddHHmmss, yyyy-MM-dd HH:mm, yyyy-MM-dd HH:mm.0] | The messages will be sent at the given scheduled time | No | null |
scheduled_delivery_timezone | Timezone(IANA time zone) | Optional timezone applied to scheduled_delivery_time date |
No | - |
order_id | String (max 32 chars, accepts only any letters, numbers, underscore, dot and dash) | Specifies a custom order ID | No | Generated UUID |
returnCredits | Bool | Returns the number of credits used instead of the number of messages. i.e. when message is more than 160 chars long more than one credit is used | No | “false” |
returnRemaining | Bool | Returs the number of remaining SMSs | No | false |
allowInvalidRecipients | Bool | Sending to an invalid recipient does not block the operation | No | false |
encoding | String (“gsm” or “ucs2”) | The SMS encoding. Use UCS2 for non standard character sets | No | “gsm” |
id_landing | int | The id of the published page. Also add the %PAGESLINK____________% placeholder in the message body |
No | - |
campaign_name | String | The campaign name | No | - |
max_fragments | int | The number of maximum fragments allowed per sms | No | Configured by user in settings page, Default 7 |
truncate | Bool | True, truncates any message exceeding max_fragments, False doesn’t send any overly long sms | No | Configured by user in settings page, Default true |
validity_period_min | int | Period after which the SMS message will be deleted from the SMS center. Please note the set expiry time may not be honoured by some mobile networks. | No | - |
richsms_url | String | The url where the rich url redirects. Also add the %RICHURL________% placeholder in the message body |
No | - |
Returns
Code | Description |
---|---|
200 | Successful request |
400 | Groups could not be found, or other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get SMS message state
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"recipient_number": 1,
"result": "OK",
"recipients": [
{
"status": "WAITING",
"message": "Text message",
"destination": "+443471234567",
"delivery_date": "20180307175609",
"first_click_date": "yyyyMMddHHmmss","// (Optional, present for Rich SMS) When the embedded link was clicked first"
"last_click_date": "yyyyMMddHHmmss", "// (Optional, present for Rich SMS) When the embedded link was clicked last"
"total_clicks": "561" "// (Optional, present for Rich SMS) Total number of clicks on the link"
}
]
}
Get informations on the SMS delivery status of the given order_id
.
HTTP request
GET /API/v1.0/REST/sms/UserParam{order_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
order_id | String | The order ID | Yes | - |
Returns
Code | Description |
---|---|
200 | A Json object representing the status of the given SMS order. |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The order_id was not found |
Possible returned statuses are:
Status | Value |
---|---|
WAITING | “WAITING” |
SENT_TO_SMSC | “SENT” |
WAITING_DELIVERY | “WAIT4DLVR” |
SENT | “SENT” |
DELIVERY_RECEIVED | “DLVRD” |
TOO_MANY_SMS_FROM_USER | “TOOM4USER” |
TOO_MANY_SMS_FOR_NUMBER | “TOOM4NUM” |
ERROR | “ERROR” |
TIMEOUT | “TIMEOUT” |
UNPARSABLE_RCPT | “UNKNRCPT” |
UNKNOWN_PREFIX | “UNKNPFX” |
SENT_IN_DEMO_MODE | “DEMO” |
WAITING_DELAYED | “SCHEDULED” |
INVALID_DESTINATION | “INVALIDDST” |
NUMBER_BLACKLISTED | “BLACKLISTED” |
NUMBER_USER_BLACKLISTED | “BLACKLISTED” |
SMSC_REJECTED | “KO” |
INVALID_CONTENTS | “INVALIDCONTENTS” |
Enable webhook on SMS delivery received
Once an SMS has been fully processed the system is able to notify the customer through a webhook that will pass data about the final status of each sent SMS.
The callback URL for the webhook can be actually set only from the UI of the application, in “My Account” -> “API & MAIL2SMS”, and it is possible to specify an HTTP method between GET or POST.
The URL callback are called passing the following parameters:
HTTP Webhook Request
POST/GET {user_defined_callback_url}
Parameters (both POST and GET webhook)
Parameter | Type | Description | Format |
---|---|---|---|
delivery_date | String | SMS Delivery notification time | Date formatted as [“yyyyMMddHHmmss”] Es. [20191224142730] |
order_id | String | SMS Identifier assigned by the user | |
status | String | The final sms status | Description of SMS internal status - See Sms final statuses |
recipient | String | SMS destination number. The recipients’ numbers must be in the international format (+443471234567 or 00443471234567) |
GET Method Webhook query params
When webhook method is GET the delivery parameters will be passed as query string in the callback url specified by the user
Example GET request performed by the platform in curl format
curl -XGET {user_defined_callback_url}?delivery_date=20210304131941&recipient=%2B393402744643&order_id=258FA1729DC242888CCFC8050B4BE8BE&status=DLVRD -H 'Content-Type: application/json'
POST Webhook Body fields
When webhook method is POST delivery parameters will be passed in the response body as x-www-form-urlencoded params
Example POST request performed by the platform in curl format
curl -d "delivery_date=20210304131941&recipient=%2B393402744643&order_id=258FA1729DC242888CCFC8050B4BE8BE&status=DLVRD" -H "Content-Type: application/x-www-form-urlencoded" -XPOST {user_defined_callback_url}
Delete a scheduled message
# Session Key example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.delete("https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("DELETE");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}',
method: 'DELETE',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}")
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Delete.new(uri.request_uri)
request['Content-type'] = 'application/json'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}", "DELETE", new NameValueCollection());
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/sms/UserParam{order_id}";
my $req = HTTP::Request->new(DELETE => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{"result":"OK"}
Deletes the SMS delivery process of the given order_id
.
HTTP request
DELETE /API/v1.0/REST/sms/UserParam{order_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
order_id | String | The order id | Yes | - |
Returns
Code | Description |
---|---|
200 | Scheduled Message deletion accepted |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The given order_id was not found, or the message sending could not be removed (e.g. Message status is not “SCHEDULED”) |
Bulk Delete of all scheduled messages
# Session Key example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/sms/bulk' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/sms/bulk' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.delete("https://api.textanywhere.com/API/v1.0/REST/sms/bulk", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/sms/bulk");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("DELETE");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/sms/bulk');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/sms/bulk',
method: 'DELETE',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/sms/bulk")
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Delete.new(uri.request_uri)
request['Content-type'] = 'application/json'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/sms/bulk", "DELETE", new NameValueCollection());
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/sms/bulk";
my $req = HTTP::Request->new(DELETE => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
Sample of a success response (orderId omitted when not present):
{
"successItems": [
{
"id": "bdfad312-9b41-4219-a52e-c0db49fe4672"
},
{
"id": "06a0a40b-382f-40d4-88b4-651c8de0ae9d",
"orderId": "06a0a40b"
},
{
"id": "3ed943d5-25e0-49c9-8373-9bb4864628e0",
"orderId": "3ed943d5"
}
]
}
Sample of a response with success and failed items (orderId omitted when not present):
{
"failedItems": [
{
"id": "bdfad312-9b41-4219-a52e-c0db49fe4672",
"failure": "Error in refunding credit",
"orderId": "bdfad312"
}
],
"successItems": [
{
"id": "06a0a40b-382f-40d4-88b4-651c8de0ae9d",
"orderId": "06a0a40b"
},
{
"id": "3ed943d5-25e0-49c9-8373-9bb4864628e0",
"orderId": "3ed943d5"
}
]
}
Bulk Delete of all SMS delivery process of the user.
HTTP request
DELETE /API/v1.0/REST/sms/bulk
Returns
Code | Description |
---|---|
200 | Scheduled Message bulk deletion accepted |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] No message found to delete, no messages are in status “SCHEDULED”. |
SMS History API
This API is used to retrieve the SMS messages sending history.
Get sent SMS history
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/smshistory?from=UserParam{date}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/smshistory?from=UserParam{date}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/smshistory?from=UserParam{date}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/smshistory?from=UserParam{date}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/smshistory?from=UserParam{date}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/smshistory?from=UserParam{date}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/smshistory?from=UserParam{date}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/smshistory?from=UserParam{date}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/smshistory?from=".uri_escape("UserParam{date}")."";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"total": 1, "// The total number of results"
"pageNumber": 1, "// The returned page number"
"result": "OK", "// The status of the request"
"pageSize": 10, "// The page size"
"smshistory": [ "// The SMS history"
{
"order_id" : "XYZABCQWERTY", "// The order ID"
"create_time" : "yyyyMMddHHmmss", "// When the order was created"
"schedule_time" : "yyyyMMddHHmmss", "// When the sending is scheduled"
"message_type" : "GP", "// The message type",
"message": "Text message",
"sender" : "MySender", "// The sender's alias"
"num_recipients" : 2 "// The number of recipients"
},
{
...
}
]
}
Returns the user’s SMS messages history
HTTP request
GET /API/v1.0/REST/smshistory?from=UserParam{fromdate}&to=UserParam{todate}&pageNumber=UserParam{page}&pageSize=UserParam{size}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
from | Date(yyyyMMddHHmmss) | Return results from the given date | Yes | - |
to | Date(yyyyMMddHHmmss) | Return results up to the given date | No | now |
timezone | Timezone(IANA time zone) | Optional timezone applied to from or to dates |
No | - |
pageNumber | Int | Return the given results page | No | 1 |
pageSize | Int | The number of results in a page | No | 10 |
Returns
Code | Description |
---|---|
200 | A paginated list of the SMS history filtered as specified by the from and to dates. |
400 | from parameter not specified, or an error in the from , to or timezone date format. Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get sent SMS to a recipient
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=UserParam{recipient}&from=UserParam{date}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=UserParam{recipient}&from=UserParam{date}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=UserParam{recipient}&from=UserParam{date}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=UserParam{recipient}&from=UserParam{date}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=UserParam{recipient}&from=UserParam{date}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=UserParam{recipient}&from=UserParam{date}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=UserParam{recipient}&from=UserParam{date}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=UserParam{recipient}&from=UserParam{date}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=".uri_escape("UserParam{recipient}")."&from=".uri_escape("UserParam{date}")."";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"total": 1, "// The total number of results"
"pageNumber": 1, "// The returned page number"
"result": "OK", "// The status of the request"
"pageSize": 10, "// The page size"
"rcpthistory": [ "// The SMS history"
{
"order_id" : "XYZABCQWERTY", "// The order ID"
"create_time" : "yyyyMMddHHmmss", "// When the order was created"
"schedule_time" : "yyyyMMddHHmmss", "// When the sending is scheduled"
"message_type" : "GP", "// The message type"
"sender" : "MySender", "// The sender's alias"
"campaign_name": "MyCampaign", "// The campaign name"
"send_time": "yyyyMMddHHmmss", "// When the message is sent"
"delivery_time": "yyyyMMddHHmmss", "// When the message is arrive to the phone"
"status": 4, "// Status of message"
"destination": "+XXXXXXXXXX", "// Recipient number"
"first_click_date": "yyyyMMddHHmmss","// (Optional, present for Rich SMS) When the embedded link was clicked first"
"last_click_date": "yyyyMMddHHmmss", "// (Optional, present for Rich SMS) When the embedded link was clicked last"
"total_clicks": "561" "// (Optional, present for Rich SMS) Total number of clicks on the link"
},
{
...
}
]
}
Returns the user’s SMS messages history for the specified recipient
HTTP request
GET /API/v1.0/REST/rcptHistory?recipient=UserParam{recipient}&from=UserParam{fromdate}&to=UserParam{todate}&pageNumber=UserParam{page}&pageSize=UserParam{size}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
recipient | Recipient in ‘+cnnnnnnn’ format where c is country prefix and n the digits of the number | Return status only of sms sent to this number | Yes | - |
from | Date(yyyyMMddHHmmss) | Return results from the given date | Yes | - |
to | Date(yyyyMMddHHmmss) | Return results up to the given date | No | now |
timezone | Timezone(IANA time zone) | Optional timezone applied to from or to dates |
No | - |
pageNumber | Int | Return the given results page | No | 1 |
pageSize | Int | The number of results in a page | No | 10 |
Returns
Code | Description |
---|---|
200 | A paginated list of the SMS history filtered as specified by recipient and the from /to dates. |
400 | recipient or from parameter not specified, or an error in the from , to or timezone date format. Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get sent Rich SMS statistics
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=UserParam{order_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=UserParam{order_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=UserParam{order_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=UserParam{order_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=UserParam{order_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=UserParam{order_id}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=UserParam{order_id}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=UserParam{order_id}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=".uri_escape("UserParam{order_id}")."";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"summary": { "// Summary data of the clicks on the links for this sms campaign"
"uniqueClicks": 124, "// How many recipients clicked on the sms link"
"totalClicks": 172, "// Total number of clicks (a single recipient can click multiple times)"
"sentShortUrls": 200, "// Total messages sent with a correct link inside"
"percentageClickedOnSent": 62 "// uniqueClicks / sentShortUrls"
},
"aggregate": { "// Data aggregated by how the links were opened"
"total": 4, "// Total messages sent with a correct link inside"
"os": { "// Operating System used when opening the link (Microsoft, Linux, Android)"
"Linux": {
"clicks": 14,
"percentage": 12
},
"Android": {
"clicks": 110,
"percentage": 88
}
},
"browser": { "// Browser used when opening the link (Chrome, Firefox, Safari)"
"Unknown": {
"clicks": 15,
"percentage": 12
},
"Chrome 8": {
"clicks": 66,
"percentage": 53
},
"Firefox": {
"clicks": 43,
"percentage": 35
}
},
"device": { "// Device used when opening the link (Computer, Mobile)"
"Mobile": {
"clicks": 110,
"percentage": 88
},
"Computer": {
"clicks": 14,
"percentage": 12
}
}
}
}
After sending an sms campaign via API containing a Rich sms shortened link, this api returns that sms link’s opening statistics.
Keep in mind that you need to use a unique order_id
when sending and store it to request in the near future.
HTTP request
GET /API/v1.0/REST/smsrich/statistics?order_id=UserParam{order_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
order_id | String | The order_id specified when sending the message | Yes | - |
Returns
Code | Description |
---|---|
200 | Summury and aggregated data for the link opening if the message specified exists. |
400 | order_id parameter not specified, or no message identified by it |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
SMS Blacklist / Stop SMS
This is the part of the API that allow to insert and to retrieve the list of SMS blacklist / Stop SMS. The SMS blacklist contains the phone numbers to which you don’t want to send any SMS. If the Stop SMS Service is active, any person who receive an SMS can add their phone number to the blacklist.
Add phone number to blacklist.
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=UserParam{phoneNumber}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=UserParam{phoneNumber}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=UserParam{phoneNumber}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=UserParam{phoneNumber}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=UserParam{phoneNumber}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=UserParam{phoneNumber}',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=UserParam{phoneNumber}")
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=UserParam{phoneNumber}", "POST", null);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=".uri_escape("UserParam{phoneNumber}")."";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
true
Add phone number to SMS blacklist. The phone number will no longer receive an SMS from the user requesting the addition to the blacklist.
HTTP request
POST /API/v1.0/REST/blacklist/sms
Query params
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
phoneNumber | String | The phone number of the user. The format must be +441234567890 or 00441234567890 | Yes | - |
Returns
Code | Description |
---|---|
200 | The phone number is successfully added. |
400 | [Bad request] Invalid recipient. |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Add multiple numbers to sms blacklist
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
[
"+4434015546",
"+4434025546"
]
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
[
"+4434015546",
"+4434025546"
]
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """[
"+4434015546",
"+4434025546"
]"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "[" +
" \"+4434015546\", " +
" \"+4434025546\"" +
"]";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '[' .
' "+4434015546", ' .
' "+4434025546"' .
']';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: [
"+4434015546",
"+4434025546"
],
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch")
payload = [
"+4434015546",
"+4434025546"
]
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "[" +
" \"+4434015546\", " +
" \"+4434025546\"" +
"]";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch", "POST", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = [
"+4434015546",
"+4434025546"
];
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
2
Add multiple numbers to the user’s blacklist.
HTTP request
POST /API/v1.0/REST/blacklist/smsbatch
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
— | List(String) | Array of phone numbers | Yes | “” |
Returns
Code | Description |
---|---|
200 | Number of phone numbers correctly put in the blacklist |
400 | Some of the phone numbers specified were badly formatted |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Retrieve list of phone numbers in blacklist
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=UserParam{from}&to=UserParam{to}&origins=UserParam{origins}&pageNumber=UserParam{pageNumber}&pageSize=UserParam{pageSize}&number=UserParam{number}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=UserParam{from}&to=UserParam{to}&origins=UserParam{origins}&pageNumber=UserParam{pageNumber}&pageSize=UserParam{pageSize}&number=UserParam{number}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=UserParam{from}&to=UserParam{to}&origins=UserParam{origins}&pageNumber=UserParam{pageNumber}&pageSize=UserParam{pageSize}&number=UserParam{number}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=UserParam{from}&to=UserParam{to}&origins=UserParam{origins}&pageNumber=UserParam{pageNumber}&pageSize=UserParam{pageSize}&number=UserParam{number}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=UserParam{from}&to=UserParam{to}&origins=UserParam{origins}&pageNumber=UserParam{pageNumber}&pageSize=UserParam{pageSize}&number=UserParam{number}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=UserParam{from}&to=UserParam{to}&origins=UserParam{origins}&pageNumber=UserParam{pageNumber}&pageSize=UserParam{pageSize}&number=UserParam{number}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=UserParam{from}&to=UserParam{to}&origins=UserParam{origins}&pageNumber=UserParam{pageNumber}&pageSize=UserParam{pageSize}&number=UserParam{number}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=UserParam{from}&to=UserParam{to}&origins=UserParam{origins}&pageNumber=UserParam{pageNumber}&pageSize=UserParam{pageSize}&number=UserParam{number}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=".uri_escape("UserParam{from}")."&to=".uri_escape("UserParam{to}")."&origins=".uri_escape("UserParam{origins}")."&pageNumber=".uri_escape("UserParam{pageNumber}")."&pageSize=".uri_escape("UserParam{pageSize}")."&number=".uri_escape("UserParam{number}")."";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"totalElements": 3, "// The total number of results"
"totalPages": 1, "// The total pages of results"
"last": true, "// Is last page"
"first": true, "// Is first page"
"size": 10, "// Page size"
"number": 0, "// Page number"
"sort": null, "// Sort"
"numberOfElements": 3, "// Number of element in page"
"content": [
{
"number": "+44123456789", "// The complete phone number"
"idNation": "ita", "// The nation of phone number"
"rcptPrefix": "123", "// The operator prefix"
"rcptNumber": "456789", "// The number"
"origin": "API", "// Origin of insert (API, WEB, STOPSMS)"
"insertTime": "2018-10-10 08:00:00" "// The datetime of insert in blacklist"
},
{
...
}
]
}
Retrieve the paginated list of Phone numbers in SMS Blacklist
HTTP request
GET /API/v1.0/REST/blacklist/sms
Query params
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
from | Date(yyyy-MM-dd HH:mm:ss) | Return results from the given date | No | - |
to | Date(yyyy-MM-dd HH:mm:ss) | Return results up to the given date | No | - |
timezone | Timezone(IANA time zone) | Optional timezone applied to from or to dates |
No | - |
number | String | Return results that contain this phone number or part of it. | No | - |
origins | String | List of origins(API, WEB, STOPSMS) separated by ‘,’ used for filter the results | No | - |
pageNumber | String | Return the given results page | No | - |
pageSize | String | The number of results in a page | No | - |
Returns
Code | Description |
---|---|
200 | A paginated list of phone number in blacklist. |
400 | Some of the parameters specified were badly formatted |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Received SMS API
This API allows to query the received SMS messages on the owned SIMs.
Get new received messages
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result": "OK",
"srsmshistory": [
{
"id_message": "31",
"id_sim": "+443400000001",
"sender": "+443356242290",
"message": "sadasd",
"sms_date": "20160503102231",
"keyword": "qwe"
},
{
"id_message": "29",
"id_sim": "+443400000001",
"sender": "+443356242290",
"message": "sadasd",
"sms_date": "20160503102231",
"keyword": "qwe"
}
]
}
Returns the list of received messages on the given sim_id
since the
last call of this method, or the beginning of time if it’s the first
call. The list is limited to max. 100 entries.
HTTP request
For all SIMs, use:
GET /API/v1.0/REST/newsrsmsmessage?limit=UserParam{limit}
For one or more specific SIMs, use:
GET /API/v1.0/REST/newsrsmsmessage/UserParam{id_sim}?limit=UserParam{limit}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
id_sim | String(PhoneNumber) | The phone number where you enabled the service of reception, in international format (+443471234567 or 00443471234567). If no SIM is specified, returns the new messages for all enabled SIMs. It is possible to specify more numbers, separated by comma | No | All SIMs |
limit | Int (max 100) | The max. number of entries returned | No | 100 |
Returns
Code | Description |
---|---|
200 | The list of received SMS messages since the last call of this method. |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get the received SMS messages
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=UserParam{from_date}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=UserParam{from_date}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=UserParam{from_date}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=UserParam{from_date}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=UserParam{from_date}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=UserParam{from_date}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=UserParam{from_date}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=UserParam{from_date}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=".uri_escape("UserParam{from_date}")."";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result": "OK",
"srsmshistory": [
{
"id_message": "2",
"id_sim": "+443400000001",
"sender": "+443356242290",
"message": "abcde",
"sms_date": "20160503102231",
"keyword": ""
}
],
"pageNumber": 1,
"pageSize": 10,
"total": 1
}
Get the paginated list of received SMS messages.
HTTP request
For all SIMs, use:
GET /API/v1.0/REST/srsmshistory?from=UserParam{fromdate}&to=UserParam{todate}&pageNumber=UserParam{page}&pageSize=UserParam{size}
For one or more specific SIMs, use:
GET /API/v1.0/REST/srsmshistory/{id_sim}?from={fromdate}&to={todate}&pageNumber={page}&pageSize={size}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
id_sim | String(PhoneNumber) | The phone number where you enabled the service of reception, in international format (+443471234567 or 00443471234567). If no SIM is specified, returns the new messages for all enabled SIMs. It is possible to specify more numbers, separated by comma | No | All SIMs |
from | Date(yyyyMMddHHmmss) | Return results from the given date | Yes | - |
to | Date(yyyyMMddHHmmss) | Return results up to the given date | No | now |
timezone | Timezone(IANA time zone) | Optional timezone applied to from or to dates |
No | - |
pageNumber | Int | Return the given results page | No | 1 |
pageSize | Int | The number of results in a page | No | 10 |
Returns
Code | Description |
---|---|
200 | The paginated list of received SMS messages. |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get the received SMS messages after a specified message.
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/srsmshistory/UserParam{id_sim}/UserParam{id_message}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/srsmshistory/UserParam{id_sim}/UserParam{id_message}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/srsmshistory/UserParam{id_sim}/UserParam{id_message}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/srsmshistory/UserParam{id_sim}/UserParam{id_message}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/srsmshistory/UserParam{id_sim}/UserParam{id_message}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/srsmshistory/UserParam{id_sim}/UserParam{id_message}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/srsmshistory/UserParam{id_sim}/UserParam{id_message}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/srsmshistory/UserParam{id_sim}/UserParam{id_message}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/srsmshistory/UserParam{id_sim}/UserParam{id_message}";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result": "OK",
"srsmshistory": [
{
"id_message": "6",
"id_sim": "+443400000000",
"sender": "+443356242290",
"message": "abcdef",
"sms_date": "20160503102231",
"keyword": ""
},
{
"id_message": "7",
"id_sim": "+443400000000",
"sender": "+443356242290",
"message": "abcdef",
"sms_date": "20160503102231",
"keyword": ""
},
{
"id_message": "8",
"id_sim": "+443400000000",
"sender": "+443356242290",
"message": "abcdef",
"sms_date": "20160503102231",
"keyword": ""
}
]
}
Returns a list (limited to max. 100 entries) of SMS messages received
after the given SMS message ID id_message
, for the given SIM id_sim
.
HTTP request
GET /API/v1.0/REST/srsmshistory/UserParam{id_sim}/UserParam{id_message}?limit=UserParam{limit}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
id_sim | String (Phone number) | The phone number where you enabled the service of reception, in international format (+443471234567 or 00393471234567) | Yes | - |
id_message | Int | The reference message ID | Yes | - |
limit | Int (max. 100) | The max. number of entries in the returned list | No | 100 |
Returns
Code | Description |
---|---|
200 | The list of received SMS messages after the given message. |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get the MO received messages.
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/mosmshistory' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/mosmshistory' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/mosmshistory", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/mosmshistory");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/mosmshistory');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/mosmshistory',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/mosmshistory")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/mosmshistory");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/mosmshistory";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
{
"result": "OK",
"srsmshistory": [
{
"id_message": "6",
"id_sim": "SMS STOP",
"sender": "+443356242290",
"message": "STOP asd",
"sms_date": "20160503102231",
"keyword": ""
},
{
"id_message": "7",
"id_sim": "SMS STOP",
"sender": "+443356242290",
"message": "STOP abcdef",
"sms_date": "20160503102231",
"keyword": ""
}
]
}
This feature is available only for French customers!
Returns a list (limited to max. 100 entries) of MO messages received for the given type
which must be STOP
or CONTACT
or OTHER
;
type
is a mandatory parameter, the others are optional.
HTTP request
GET /API/v1.0/REST/mosmshistory?type=UserParam{type}&from=UserParam{fromdate}&to=UserParam{todate}&pageNumber=UserParam{page}&pageSize=UserParam{size}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
type | String (“STOP” or “CONTACT” or “OTHER”) | Type of the MO, which must be one of STOP, CONTACT or OTHER | Yes | - |
from | Date(yyyyMMddHHmmss) | Return results from the given date | No | - |
to | Date(yyyyMMddHHmmss) | Return results up to the given date | No | - |
timezone | Timezone(IANA time zone) | Optional timezone applied to from or to dates |
No | - |
pageNumber | Int | Return the given results page | No | 1 |
pageSize | Int | The number of results in a page | No | 10 |
Returns
Code | Description |
---|---|
200 | The list of received MO messages of type, with the specified time constraints (if any) and paging |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided, or the user is not French |
404 | [Not found] The User_key was not found |
SMS template API
This is the part of the API that allows to create message templates.
Create a new template
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/template' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"name": "my template-1",
"text": "Hello World!",
"encoding": "GSM",
"sender": "my sender"
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/template' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"name": "my template-1",
"text": "Hello World!",
"encoding": "GSM",
"sender": "my sender"
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"name": "my template-1",
"text": "Hello World!",
"encoding": "GSM",
"sender": "my sender"
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/template", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/template");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"name\": \"my template-1\", " +
" \"text\": \"Hello World!\", " +
" \"encoding\": \"GSM\", " +
" \"sender\": \"my sender\"" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "name": "my template-1", ' .
' "text": "Hello World!", ' .
' "encoding": "GSM", ' .
' "sender": "my sender"' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/template');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/template',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"name": "my template-1",
"text": "Hello World!",
"encoding": "GSM",
"sender": "my sender"
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/template")
payload = {
"name": "my template-1",
"text": "Hello World!",
"encoding": "GSM",
"sender": "my sender"
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"name\": \"my template-1\", " +
" \"text\": \"Hello World!\", " +
" \"encoding\": \"GSM\", " +
" \"sender\": \"my sender\"" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/template", "POST", payload);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/template";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"name" => "my template-1",
"text" => "Hello World!",
"encoding" => "GSM",
"sender" => "my sender"
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the result of the operation and the id of the new template:
{
"idTemplate": 1,
"encoding": "GSM",
"name": "my template-1",
"text": "Hello World!",
"sender": "my sender",
"richUrl": null,
"idPage": null,
"sharingInfo": null
}
Creates a new message template.
Landing Pages URLs
It is possible to include a link to a published Landing Page by
specifying the id_landing
parameter and by adding the following
placeholder in the message body: %PAGESLINK____________%
.
Landing pages must be first created and published in your user
panel, since you will need id_landing
to send it.
A list of published landing pages can be retrieved by using the Landing Pages APIs
SMS Link Analytics
When including URLs in the message, it may be convenient to use our SMS Link Analytics short URLs service to limit the number of characters used in the SMS message and having statistic on clic.
Our API can automatically generate a short link starting from a long one, and add it in the message.
To use this feature, use the %RICHURL________%
placeholder in the message body, that will be replaced with the generated short link, and the respective richsms_url parameter, that should be set to a valid URL.
Sender Alias
Alphanumeric aliases are required to be registered first, and need to be approved both from Us and AGCOM.
Aliases can be used only with high-quality message types.
HTTP request
POST /API/v1.0/REST/template
Body fields
The body must contain a Json with all the template info:
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
name | String | Name of template | Yes | |
text | String (max 1000 chars with “gsm” encoding, 450 with “ucs2” encoding) | The body of the message. *Message max length could be 160 chars when using low-quality SMSs. New line char needs to be codified as “\n”. | Yes | - |
encoding | String (“GSM” or “UCS2”) | The SMS encoding. Use UCS2 for non standard character sets. | Yes | - |
sender | String | The Sender name. If the message type allows a custom TPOA and the field is left empty, the user’s preferred TPOA is used. Must be empty if the message type does not allow a custom TPOA. | No | - |
richUrl | String | The url where the rich url redirects. Also add the %RICHURL________% placeholder in the message body. |
No | - |
idPage | Int | The id of the published page. Also add the %PAGESLINK____________% placeholder in the message body. |
No | - |
Returns
Code | Description |
---|---|
200 | Successful request |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get all templates
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/template' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/template' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/template", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/template");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/template');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/template',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/template")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/template");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/template";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
[
{
"idTemplate": 1,
"encoding": "GSM",
"name": "my template-1",
"text": "Hello World!",
"sender": "my sender",
"richUrl": null,
"idPage": null,
"sharingInfo": null
},
{
"idTemplate": 2,
"encoding": "GSM",
"name": "my template-2",
"text": "Hello World!",
"sender": "my sender",
"richUrl": null,
"idPage": null,
"sharingInfo": null
},
]
Returns a list of the user’s message templates.
HTTP request
GET /API/v1.0/REST/template
Returns
Code | Description |
---|---|
200 | The list of the user’s templates |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get a specific template
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template}";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"idTemplate": 390,
"encoding": "GSM",
"name": "my template",
"text": "Hello World!",
"sender": "my sender",
"richUrl": null,
"idPage": null,
"sharingInfo": null
}
Returns the data of the user’s template ID.
HTTP request
GET /API/v1.0/REST/template/UserParam{template_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
template_id | Int | The template ID | Yes | - |
Returns
Code | Description |
---|---|
200 | The requested Template data |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The template was not found |
Modify an existing template
# Session Key example
curl -XPATCH 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{group_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
[
{
"op": "replace",
"path": "/text",
"value": "new message"
}
]
'
# Access token example
curl -XPATCH 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{group_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
[
{
"op": "replace",
"path": "/text",
"value": "new message"
}
]
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """[
{
"op": "replace",
"path": "/text",
"value": "new message"
}
]"""
r = requests.patch("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{group_id}", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{group_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("PATCH");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "[" +
" {" +
" \"op\": \"replace\", " +
" \"path\": \"/text\", " +
" \"value\": \"new message\"" +
" }" +
"]";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '[' .
' {' .
' "op": "replace", ' .
' "path": "/text", ' .
' "value": "new message"' .
' }' .
']';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{group_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{group_id}',
method: 'PATCH',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: [
{
"op": "replace",
"path": "/text",
"value": "new message"
}
],
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{group_id}")
payload = [
{
"op": "replace",
"path": "/text",
"value": "new message"
}
]
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Patch.new(uri.request_uri)
request['Content-type'] = 'application/json'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "[" +
" {" +
" \"op\": \"replace\", " +
" \"path\": \"/text\", " +
" \"value\": \"new message\"" +
" }" +
"]";
wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{group_id}", "DELETE", new NameValueCollection());
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/template/UserParam{group_id}";
my $req = HTTP::Request->new(PATCH => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = [
{
"op" => "replace",
"path" => "/text",
"value" => "new message"
}
];
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"idTemplate": 12,
"encoding": "GSM",
"name": "template-name",
"text": "new message",
"sender": null,
"richUrl": null,
"idPage": null,
"sharingInfo": null
}
Updates a given user’s message template
HTTP request
PATCH /API/v1.0/REST/template/UserParam{template_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
template_id | Int | The template ID | Yes | - |
Body fields
The body must contain a Json Array with the operation to perform on a specific template:
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
op | String (“add”, “remove”, “replace”, “move”, “copy”, “test”) | The patch operation supported by JSON Patch. | Yes | - |
path | String | JSON Pointer to specify the part of the document to operate on. | Yes | - |
value | String | JSON Value used in combination with some specific operation (“add”, “replace”). Affects the value indicated by the path. | Yes | - |
Returns
Code | Description |
---|---|
200 | The updated Template data |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The template was not found |
Remove a template
# Session Key example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.delete("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("DELETE");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template_id}',
method: 'DELETE',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template_id}")
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Delete.new(uri.request_uri)
request['Content-type'] = 'application/json'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template_id}", "DELETE", new NameValueCollection());
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/template/UserParam{template_id}";
my $req = HTTP::Request->new(DELETE => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result": "OK"
}
Deletes the given user’s message template.
HTTP request
DELETE /API/v1.0/REST/template/UserParam{template_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
template_id | Int | The template ID | Yes | - |
Returns
Code | Description |
---|---|
200 | Template successfully deleted |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The template was not found |
Subaccount API
If enabled as a superaccount, the user can create subaccounts that can be assigned to third-parties. Superaccounts may or may not share credits with their subaccounts.
Get the list of subaccounts
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccounts' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccounts' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccounts", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccounts");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccounts');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccounts',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccounts")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccounts");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccounts";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result": "OK",
"pageNumber": 1,
"pageSize": 10,
"total": 2,
"subaccount": [
{
"activation-time": "20160823",
"active": true,
"address": "via viotta",
"allowtpoavalidation": true,
"cell": "+443385958233",
"city": "Città ",
"fiscal-code": "PRRFCC92L09L488E",
"pa-code": null,
"company": false,
"company-name": null,
"create-time": "20160823",
"credit-eat-mode": 2,
"credits-sum": "€ 0,000",
"default-message-type": "SI",
"default-nation": "ita",
"dfeu": true,
"email": "prova@prova.pr",
"fax": "0461757575",
"foreign": false,
"id-user": 5,
"invoicing-email": null,
"language": "ita",
"legal-agreement-time": "20160823",
"legalAgreementVersion": 0,
"login": "logon",
"max-subaccounts": -1,
"name": "nome",
"num-cell-for-test-sms": "+443385958233",
"partner": false,
"partner-code": null,
"phone": "0461757575",
"piva": null,
"preferred-tpoa": "+443385958233",
"private": true,
"province": "Trento",
"referral": false,
"shop_cart_check": true,
"split-payment": false,
"subaccount": true,
"subaccount-types": 0,
"super-account-name": "",
"superaccount": false,
"surname": "asdasd",
"use24": true,
"user-nation": "ita",
"zip-code": "38010",
"registration-email": "regemail@regemail.re",
"credits": [
{
"id": "GP",
"qty": 10
},
{
"id": "GS",
"qty": 10
},
{
"id": "EE",
"qty": 10
}
]
}
]
}
Returns the list of subaccounts of the authenticated user.
HTTP request
GET /API/v1.0/REST/subaccounts?pageNumber=UserParam{page}&pageSize=UserParam{size}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
pageNumber | Int | Return the given results page | No | 1 |
pageSize | Int | The number of results in a page | No | 10 |
Returns
Code | Description |
---|---|
200 | The paginated list of subaccounts of the authenticated user |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
The “credits” and “credits-sum” fields will be populated only where the subaccount has “credit-eat-mode” = 2
Create a subaccount
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"address": "via xxx",
"cell": "+443393939393",
"city": "myCity",
"fiscal-code": "BRGRJM87J89JH907E",
"company": true,
"company-name": "myCompany",
"credit-eat-mode": 1,
"dfeu": true,
"email": "em@a.il",
"fax": "0461686868",
"invoicing-email": "em@a.il",
"language": "ita",
"login": "myLogin",
"name": "myNome",
"num-cell-for-test-sms": "+443393939393",
"password": "myPassword",
"phone": "0461656565",
"piva": "104456015145",
"province": "TN",
"superaccount": false,
"surname": "mySurname",
"use24": true,
"zip-code": "38010",
"id-subaccount-profile": 1
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"address": "via xxx",
"cell": "+443393939393",
"city": "myCity",
"fiscal-code": "BRGRJM87J89JH907E",
"company": true,
"company-name": "myCompany",
"credit-eat-mode": 1,
"dfeu": true,
"email": "em@a.il",
"fax": "0461686868",
"invoicing-email": "em@a.il",
"language": "ita",
"login": "myLogin",
"name": "myNome",
"num-cell-for-test-sms": "+443393939393",
"password": "myPassword",
"phone": "0461656565",
"piva": "104456015145",
"province": "TN",
"superaccount": false,
"surname": "mySurname",
"use24": true,
"zip-code": "38010",
"id-subaccount-profile": 1
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"address": "via xxx",
"cell": "+443393939393",
"city": "myCity",
"fiscal-code": "BRGRJM87J89JH907E",
"company": true,
"company-name": "myCompany",
"credit-eat-mode": 1,
"dfeu": true,
"email": "em@a.il",
"fax": "0461686868",
"invoicing-email": "em@a.il",
"language": "ita",
"login": "myLogin",
"name": "myNome",
"num-cell-for-test-sms": "+443393939393",
"password": "myPassword",
"phone": "0461656565",
"piva": "104456015145",
"province": "TN",
"superaccount": false,
"surname": "mySurname",
"use24": true,
"zip-code": "38010",
"id-subaccount-profile": 1
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/subaccount", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"address\": \"via xxx\", " +
" \"cell\": \"+443393939393\", " +
" \"city\": \"myCity\", " +
" \"fiscal-code\": \"BRGRJM87J89JH907E\", " +
" \"company\": true, " +
" \"company-name\": \"myCompany\", " +
" \"credit-eat-mode\": 1, " +
" \"dfeu\": true, " +
" \"email\": \"em@a.il\", " +
" \"fax\": \"0461686868\", " +
" \"invoicing-email\": \"em@a.il\", " +
" \"language\": \"ita\", " +
" \"login\": \"myLogin\", " +
" \"name\": \"myNome\", " +
" \"num-cell-for-test-sms\": \"+443393939393\", " +
" \"password\": \"myPassword\", " +
" \"phone\": \"0461656565\", " +
" \"piva\": \"104456015145\", " +
" \"province\": \"TN\", " +
" \"superaccount\": false, " +
" \"surname\": \"mySurname\", " +
" \"use24\": true, " +
" \"zip-code\": \"38010\", " +
" \"id-subaccount-profile\": 1" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "address": "via xxx", ' .
' "cell": "+443393939393", ' .
' "city": "myCity", ' .
' "fiscal-code": "BRGRJM87J89JH907E", ' .
' "company": true, ' .
' "company-name": "myCompany", ' .
' "credit-eat-mode": 1, ' .
' "dfeu": true, ' .
' "email": "em@a.il", ' .
' "fax": "0461686868", ' .
' "invoicing-email": "em@a.il", ' .
' "language": "ita", ' .
' "login": "myLogin", ' .
' "name": "myNome", ' .
' "num-cell-for-test-sms": "+443393939393", ' .
' "password": "myPassword", ' .
' "phone": "0461656565", ' .
' "piva": "104456015145", ' .
' "province": "TN", ' .
' "superaccount": false, ' .
' "surname": "mySurname", ' .
' "use24": true, ' .
' "zip-code": "38010", ' .
' "id-subaccount-profile": 1' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"address": "via xxx",
"cell": "+443393939393",
"city": "myCity",
"fiscal-code": "BRGRJM87J89JH907E",
"company": true,
"company-name": "myCompany",
"credit-eat-mode": 1,
"dfeu": true,
"email": "em@a.il",
"fax": "0461686868",
"invoicing-email": "em@a.il",
"language": "ita",
"login": "myLogin",
"name": "myNome",
"num-cell-for-test-sms": "+443393939393",
"password": "myPassword",
"phone": "0461656565",
"piva": "104456015145",
"province": "TN",
"superaccount": false,
"surname": "mySurname",
"use24": true,
"zip-code": "38010",
"id-subaccount-profile": 1
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount")
payload = {
"address": "via xxx",
"cell": "+443393939393",
"city": "myCity",
"fiscal-code": "BRGRJM87J89JH907E",
"company": true,
"company-name": "myCompany",
"credit-eat-mode": 1,
"dfeu": true,
"email": "em@a.il",
"fax": "0461686868",
"invoicing-email": "em@a.il",
"language": "ita",
"login": "myLogin",
"name": "myNome",
"num-cell-for-test-sms": "+443393939393",
"password": "myPassword",
"phone": "0461656565",
"piva": "104456015145",
"province": "TN",
"superaccount": false,
"surname": "mySurname",
"use24": true,
"zip-code": "38010",
"id-subaccount-profile": 1
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"address\": \"via xxx\", " +
" \"cell\": \"+443393939393\", " +
" \"city\": \"myCity\", " +
" \"fiscal-code\": \"BRGRJM87J89JH907E\", " +
" \"company\": true, " +
" \"company-name\": \"myCompany\", " +
" \"credit-eat-mode\": 1, " +
" \"dfeu\": true, " +
" \"email\": \"em@a.il\", " +
" \"fax\": \"0461686868\", " +
" \"invoicing-email\": \"em@a.il\", " +
" \"language\": \"ita\", " +
" \"login\": \"myLogin\", " +
" \"name\": \"myNome\", " +
" \"num-cell-for-test-sms\": \"+443393939393\", " +
" \"password\": \"myPassword\", " +
" \"phone\": \"0461656565\", " +
" \"piva\": \"104456015145\", " +
" \"province\": \"TN\", " +
" \"superaccount\": false, " +
" \"surname\": \"mySurname\", " +
" \"use24\": true, " +
" \"zip-code\": \"38010\", " +
" \"id-subaccount-profile\": 1" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount", "POST", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"address" => "via xxx",
"cell" => "+443393939393",
"city" => "myCity",
"fiscal-code" => "BRGRJM87J89JH907E",
"company" => true,
"company-name" => "myCompany",
"credit-eat-mode" => 1,
"dfeu" => true,
"email" => "em@a.il",
"fax" => "0461686868",
"invoicing-email" => "em@a.il",
"language" => "ita",
"login" => "myLogin",
"name" => "myNome",
"num-cell-for-test-sms" => "+443393939393",
"password" => "myPassword",
"phone" => "0461656565",
"piva" => "104456015145",
"province" => "TN",
"superaccount" => false,
"surname" => "mySurname",
"use24" => true,
"zip-code" => "38010",
"id-subaccount-profile" => 1
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result": "Ok",
"idSubaccount": "10"
}
# HTTP header includes location response that points to the created subaccount:
'Location': '/subaccount/10'
Creates a new subaccount for the authenticated user, which has to be a superaccount.
HTTP request
POST /API/v1.0/REST/subaccount
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
address | String | The subaccount address | No | - |
cell | String | The subaccount mobile phone number | Yes | - |
city | String | The subaccount city | No | - |
company | Bool | DEPRECATED sub can be only a company - Is the subaccount a company? | No | true |
company-name | String | The company name | Yes (if company=true) | - |
credit-eat-mode | Int (0, 1, 2) | DEPRECATED automatically derived by the super account settings - Tells from who credits are scaled. 0 = own credits, 1 = superaccount credits, 2 = own credits and superaccount ones | No | - |
dfeu | Bool | Use the Date Format in EUropean format | No | true |
String (a valid Email) | The subaccount’s operational email. It is used to receive reports, alerts and communications. | Yes | - | |
fax | String | The subaccount FAX number | No | “” |
invoicing-email | String (a valid Email) | If provided, invoices will be sent here instead of the default email | No | “” |
language | String | The subaccount language. If none, defaults to the one of the superaccount | No | to the one of the superaccount |
login | String | The subaccount login must be a valid and unique email | Yes | - |
name | String | The subaccount owner first name | Yes | - |
num-cell-for-test-sms | String (Phone number) | A phone number where test SMS messages will be sent | No | “” |
password | String | The subaccount Web password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.) | No | If null, will be autogenerated |
passwordApi | String | The subaccount Api password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.) | No | If null, will be the same of Web password |
phone | String (PhoneNumber) | The subaccount phone number | No | “” |
piva | String | The subaccount VAT number (P.Iva in Italy) | No | |
province | String | The subaccount province | No | - |
superaccount | Bool | The subaccount is a superaccount itself (i.e. it can create his own subaccounts) | No | false |
surname | String | The subaccount last name | Yes | - |
use24 | Bool | Use the 24 hour format for time | No | true |
zip-code | String | The subaccount ZIP Code | No | - |
id-subaccount-profile | Int | Specifying a custom subaccount profile allows a superaccount to narrow down the subaccount enabled features (e.g. Only send SMS messages, or even further, only send a specific type of SMS message) | No | The default profile |
Returns
Code | Description |
---|---|
200 | Success, returns a response body specifyng the id of new subaccount and HTTP location header pointing to the created subaccount |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Edit subaccount
# Session Key example
curl -XPUT 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"address": "via xxx",
"cell": "+443393939393",
"city": "myCity",
"fiscal-code": "BRGRJM87J89JH907E",
"company": true,
"company-name": "myCompany",
"credit-eat-mode": 1,
"dfeu": true,
"email": "em@a.il",
"fax": "0461686868",
"invoicing-email": "em@a.il",
"language": "ita",
"name": "myNome",
"num-cell-for-test-sms": "+443393939393",
"password": "myPassword",
"phone": "0461656565",
"piva": "104456015145",
"province": "TN",
"superaccount": false,
"surname": "mySurname",
"use24": true,
"zip-code": "38010",
"id-subaccount-profile": 1
}
'
# Access token example
curl -XPUT 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"address": "via xxx",
"cell": "+443393939393",
"city": "myCity",
"fiscal-code": "BRGRJM87J89JH907E",
"company": true,
"company-name": "myCompany",
"credit-eat-mode": 1,
"dfeu": true,
"email": "em@a.il",
"fax": "0461686868",
"invoicing-email": "em@a.il",
"language": "ita",
"name": "myNome",
"num-cell-for-test-sms": "+443393939393",
"password": "myPassword",
"phone": "0461656565",
"piva": "104456015145",
"province": "TN",
"superaccount": false,
"surname": "mySurname",
"use24": true,
"zip-code": "38010",
"id-subaccount-profile": 1
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"address": "via xxx",
"cell": "+443393939393",
"city": "myCity",
"fiscal-code": "BRGRJM87J89JH907E",
"company": true,
"company-name": "myCompany",
"credit-eat-mode": 1,
"dfeu": true,
"email": "em@a.il",
"fax": "0461686868",
"invoicing-email": "em@a.il",
"language": "ita",
"name": "myNome",
"num-cell-for-test-sms": "+443393939393",
"password": "myPassword",
"phone": "0461656565",
"piva": "104456015145",
"province": "TN",
"superaccount": false,
"surname": "mySurname",
"use24": true,
"zip-code": "38010",
"id-subaccount-profile": 1
}"""
r = requests.put("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("PUT");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"address\": \"via xxx\", " +
" \"cell\": \"+443393939393\", " +
" \"city\": \"myCity\", " +
" \"fiscal-code\": \"BRGRJM87J89JH907E\", " +
" \"company\": true, " +
" \"company-name\": \"myCompany\", " +
" \"credit-eat-mode\": 1, " +
" \"dfeu\": true, " +
" \"email\": \"em@a.il\", " +
" \"fax\": \"0461686868\", " +
" \"invoicing-email\": \"em@a.il\", " +
" \"language\": \"ita\", " +
" \"name\": \"myNome\", " +
" \"num-cell-for-test-sms\": \"+443393939393\", " +
" \"password\": \"myPassword\", " +
" \"phone\": \"0461656565\", " +
" \"piva\": \"104456015145\", " +
" \"province\": \"TN\", " +
" \"superaccount\": false, " +
" \"surname\": \"mySurname\", " +
" \"use24\": true, " +
" \"zip-code\": \"38010\", " +
" \"id-subaccount-profile\": 1" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "address": "via xxx", ' .
' "cell": "+443393939393", ' .
' "city": "myCity", ' .
' "fiscal-code": "BRGRJM87J89JH907E", ' .
' "company": true, ' .
' "company-name": "myCompany", ' .
' "credit-eat-mode": 1, ' .
' "dfeu": true, ' .
' "email": "em@a.il", ' .
' "fax": "0461686868", ' .
' "invoicing-email": "em@a.il", ' .
' "language": "ita", ' .
' "name": "myNome", ' .
' "num-cell-for-test-sms": "+443393939393", ' .
' "password": "myPassword", ' .
' "phone": "0461656565", ' .
' "piva": "104456015145", ' .
' "province": "TN", ' .
' "superaccount": false, ' .
' "surname": "mySurname", ' .
' "use24": true, ' .
' "zip-code": "38010", ' .
' "id-subaccount-profile": 1' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}',
method: 'PUT',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"address": "via xxx",
"cell": "+443393939393",
"city": "myCity",
"fiscal-code": "BRGRJM87J89JH907E",
"company": true,
"company-name": "myCompany",
"credit-eat-mode": 1,
"dfeu": true,
"email": "em@a.il",
"fax": "0461686868",
"invoicing-email": "em@a.il",
"language": "ita",
"name": "myNome",
"num-cell-for-test-sms": "+443393939393",
"password": "myPassword",
"phone": "0461656565",
"piva": "104456015145",
"province": "TN",
"superaccount": false,
"surname": "mySurname",
"use24": true,
"zip-code": "38010",
"id-subaccount-profile": 1
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}")
payload = {
"address": "via xxx",
"cell": "+443393939393",
"city": "myCity",
"fiscal-code": "BRGRJM87J89JH907E",
"company": true,
"company-name": "myCompany",
"credit-eat-mode": 1,
"dfeu": true,
"email": "em@a.il",
"fax": "0461686868",
"invoicing-email": "em@a.il",
"language": "ita",
"name": "myNome",
"num-cell-for-test-sms": "+443393939393",
"password": "myPassword",
"phone": "0461656565",
"piva": "104456015145",
"province": "TN",
"superaccount": false,
"surname": "mySurname",
"use24": true,
"zip-code": "38010",
"id-subaccount-profile": 1
}
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Put.new(uri.request_uri)
request['Content-type'] = 'application/json'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"address\": \"via xxx\", " +
" \"cell\": \"+443393939393\", " +
" \"city\": \"myCity\", " +
" \"fiscal-code\": \"BRGRJM87J89JH907E\", " +
" \"company\": true, " +
" \"company-name\": \"myCompany\", " +
" \"credit-eat-mode\": 1, " +
" \"dfeu\": true, " +
" \"email\": \"em@a.il\", " +
" \"fax\": \"0461686868\", " +
" \"invoicing-email\": \"em@a.il\", " +
" \"language\": \"ita\", " +
" \"name\": \"myNome\", " +
" \"num-cell-for-test-sms\": \"+443393939393\", " +
" \"password\": \"myPassword\", " +
" \"phone\": \"0461656565\", " +
" \"piva\": \"104456015145\", " +
" \"province\": \"TN\", " +
" \"superaccount\": false, " +
" \"surname\": \"mySurname\", " +
" \"use24\": true, " +
" \"zip-code\": \"38010\", " +
" \"id-subaccount-profile\": 1" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}", "PUT", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}";
my $req = HTTP::Request->new(PUT => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"address" => "via xxx",
"cell" => "+443393939393",
"city" => "myCity",
"fiscal-code" => "BRGRJM87J89JH907E",
"company" => true,
"company-name" => "myCompany",
"credit-eat-mode" => 1,
"dfeu" => true,
"email" => "em@a.il",
"fax" => "0461686868",
"invoicing-email" => "em@a.il",
"language" => "ita",
"name" => "myNome",
"num-cell-for-test-sms" => "+443393939393",
"password" => "myPassword",
"phone" => "0461656565",
"piva" => "104456015145",
"province" => "TN",
"superaccount" => false,
"surname" => "mySurname",
"use24" => true,
"zip-code" => "38010",
"id-subaccount-profile" => 1
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
# # HTTP header includes location response that points to the updated subaccount:
'Location': '/subaccount/18107'
Edits the subaccount identified by the given subaccount_id
. Calling
user must be a superaccount.
HTTP request
PUT /API/v1.0/REST/subaccount/UserParam{subaccount_id}?lock-subaccount=UserParam{value}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
subaccount_id | Int | The subaccount ID | Yes | - |
lock-subaccount | Bool | Activate or deactivate the subaccount | No | false |
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
address | String | The subaccount address | No | - |
cell | String | The subaccount mobile phone number | Yes | - |
city | String | The subaccount city | No | - |
company | Bool | DEPRECATED sub can be only a company - Is the subaccount a company? | No | true |
company-name | String | The company name | Yes (if company=true) | - |
credit-eat-mode | Int (0, 1, 2) | DEPRECATED automatically derived by the super account settings - Tells from who credits are scaled. 0 = own credits, 1 = superaccount credits, 2 = own credits and superaccount ones | No | - |
dfeu | Bool | Use the Date Format in EUropean format | No | true |
String (a valid Email) | The subaccount’s operational email. It is used to receive reports, alerts and communications. | Yes | - | |
registration-email | String (a valid Email) | The subaccount’s registration email. It is used to identify the account, must be unique. | No | - |
fax | String | The subaccount FAX number | No | “” |
invoicing-email | String (a valid Email) | If provided, invoices will be sent here instead of the default email | No | “” |
language | String | The subaccount language. If none, defaults to the one of the superaccount | No | to the one of the superaccount |
name | String | The subaccount owner first name | Yes | - |
num-cell-for-test-sms | String (Phone number) | A phone number where test SMS messages will be sent | No | “” |
password | String | The subaccount password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.) | No | If null, will keep current password |
passwordApi | String | The subaccount Api password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.) | No | If null, will keep current password |
phone | String (PhoneNumber) | The subaccount phone number | No | “” |
piva | String | The subaccount VAT number (P.Iva in Italy) | No | |
province | String | The subaccount province | No | - |
superaccount | Bool | The subaccount is a superaccount itself (i.e. it can create his own subaccounts) | No | false |
surname | String | The subaccount last name | Yes | - |
use24 | Bool | Use the 24 hour format for time | No | true |
zip-code | String | The subaccount ZIP Code | No | - |
id-subaccount-profile | Int | Specifying a custom subaccount profile allows a superaccount to narrow down the subaccount enabled features (e.g. Only send SMS messages, or even further, only send a specific type of SMS message) | No | The default profile |
Returns
Code | Description |
---|---|
200 | Success, returns an empty response with the HTTP location header pointing to the updated subaccount |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Change subaccount WebApp password
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"passwd": "password"
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"passwd": "password"
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"passwd": "password"
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd", headers=headers, data=payload)
if r.status_code != 201:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"passwd\": \"password\"" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 201) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "passwd": "password"' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 201) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"passwd": "password"
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 201) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd")
payload = {
"passwd": "password"
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "201"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"passwd\": \"password\"" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd", "POST", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"passwd" => "password"
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 201) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
# The HTTP location header that points to the subaccount 'change password' URL:
'Location': '/subaccount/{subaccount_id}/changepwd'
Change a subaccount’s password
HTTP request
POST /API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
subaccount_id | Int | The subaccount ID | Yes | - |
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
passwd | String | The subaccount password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.) | Yes | - |
Returns
Code | Description |
---|---|
201 | Password correctly changed. HTTP location header pointing to the change password URL. |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Change subaccount API password
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd/api' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"passwd": "password"
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd/api' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"passwd": "password"
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"passwd": "password"
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd/api", headers=headers, data=payload)
if r.status_code != 201:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"passwd\": \"password\"" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 201) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "passwd": "password"' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd/api');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 201) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd/api',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"passwd": "password"
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 201) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd/api")
payload = {
"passwd": "password"
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "201"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"passwd\": \"password\"" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd/api", "POST", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd/api";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"passwd" => "password"
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 201) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
# The HTTP location header that points to the subaccount 'change password' URL:
'Location': '/subaccount/{subaccount_id}/changepwd/api'
Change a subaccount’s password
HTTP request
POST /API/v1.0/REST/subaccount/UserParam{subaccount_id}/changepwd/api
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
subaccount_id | Int | The subaccount ID | Yes | - |
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
passwd | String | The subaccount password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.) | Yes | - |
Returns
Code | Description |
---|---|
201 | Password correctly changed. HTTP location header pointing to the change password URL. |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get subaccount
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"activation-time": "20160823",
"active": true,
"address": "via",
"allowtpoavalidation": true,
"cell": "+443385958233",
"city": "Città ",
"fiscal-code": "FDFWEE92L45L458E",
"pa-code": null,
"company": false,
"company-name": null,
"create-time": "20160823",
"credit-eat-mode": 2,
"credits-sum": "€ 0,000",
"default-message-type": "SI",
"default-nation": "ita",
"dfeu": true,
"email": "prova@prova.pr",
"fax": "0461657575",
"foreign": false,
"id-user": 5,
"invoicing-email": null,
"language": "ita",
"legal-agreement-time": "20160823",
"legalAgreementVersion": 0,
"login": "logon",
"max-subaccounts": -1,
"name": "nome",
"num-cell-for-test-sms": "+443385958233",
"partner": false,
"partner-code": null,
"phone": "0461657575",
"piva": null,
"preferred-tpoa": "+443385958233",
"private": true,
"province": "Trento",
"referral": false,
"shop_cart_check": true,
"split-payment": false,
"subaccount": true,
"subaccount-types": 0,
"super-account-name": "",
"superaccount": false,
"surname": "asdasd",
"use24": true,
"user-nation": "ita",
"zip-code": "38010",
"registration-email": "regemail@regemail.re",
"credits": [
{
"id": "GP",
"qty": 0
},
{
"id": "GS",
"qty": 0
},
{
"id": "EE",
"qty": 0
}
]
}
Get a subaccount’s details
HTTP request
GET /API/v1.0/REST/subaccount/UserParam{subaccount_id}
Returns
Code | Description |
---|---|
200 | Successful request |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
The “credits” and “credits-sum” fields will be populated only in the case where the subaccount has “credit-eat-mode” = 2.
Get subaccount available credits
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/credit' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/credit' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/credit", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/credit");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/credit');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/credit',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/credit")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/credit");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/credit";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result": "OK",
"credits": [
{
"message-type": "GP",
"amount": 20
},
{
"message-type": "GS",
"amount": 150
}
]
}
Returns the available credits of the given subaccount
HTTP request
GET /API/v1.0/REST/subaccount/UserParam{subaccount_id}/credit
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
subaccount_id | Int or String | The subaccount ID or Login | Yes | - |
Returns
Code | Description |
---|---|
200 | Successful request, returns a JSON object with the available credits details |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get a subaccount’s purchases
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"result": "OK",
"purchases": [
{
"super-to-sub": false,
"amount": 37,
"create-time": "20160826104539",
"id_purchase": 20,
"price": 37,
"available": 0,
"message-types": [
{
"message-type": "N",
"unit-price": 1.2
}
]
},
{
"super-to-sub": true,
"amount": 37,
"create-time": "20160826103027",
"id_purchase": 20,
"price": 37,
"available": 0,
"message-types": [
{
"message-type": "GP",
"unit-price": 1.2
}
]
}
],
"pageNumber": 1,
"pageSize": 10,
"total": 2
}
Returns the paginated list of purchases made by a subaccount. Caller must be a superaccount.
HTTP request
GET /API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase?pageNumber=UserParam{page}&pageSize=UserParam{size}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
subaccount_id | Int or String | The subaccount ID or Login | Yes | - |
pageNumber | Int | Return the given results page | No | 1 |
pageSize | Int | The number of results in a page | No | 10 |
Returns
Code | Description |
---|---|
200 | The paginated list of the subaccount’s purchases |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Create a subaccount purchase
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"purchases": [
{
"super-to-sub": true,
"price": 25.0,
"message-types": [
{
"message-type": "UserParam{MESSAGE_TYPE_1}",
"unit-price": 1.1,
"nation": "UserParam{NATION_1}"
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 0.7,
"nation": "UserParam{NATION_2}"
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 1.5,
"nation": "UserParam{NATION_3}"
}
]
},
{
"super-to-sub": true,
"price": 37.0,
"message-types": [
{
"message-type": "UserParam{MESSAGE_TYPE_1}",
"unit-price": 1.2
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 0.8
}
]
}
]
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"purchases": [
{
"super-to-sub": true,
"price": 25.0,
"message-types": [
{
"message-type": "UserParam{MESSAGE_TYPE_1}",
"unit-price": 1.1,
"nation": "UserParam{NATION_1}"
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 0.7,
"nation": "UserParam{NATION_2}"
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 1.5,
"nation": "UserParam{NATION_3}"
}
]
},
{
"super-to-sub": true,
"price": 37.0,
"message-types": [
{
"message-type": "UserParam{MESSAGE_TYPE_1}",
"unit-price": 1.2
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 0.8
}
]
}
]
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"purchases": [
{
"super-to-sub": true,
"price": 25.0,
"message-types": [
{
"message-type": "UserParam{MESSAGE_TYPE_1}",
"unit-price": 1.1,
"nation": "UserParam{NATION_1}"
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 0.7,
"nation": "UserParam{NATION_2}"
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 1.5,
"nation": "UserParam{NATION_3}"
}
]
},
{
"super-to-sub": true,
"price": 37.0,
"message-types": [
{
"message-type": "UserParam{MESSAGE_TYPE_1}",
"unit-price": 1.2
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 0.8
}
]
}
]
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"purchases\": [" +
" {" +
" \"super-to-sub\": true, " +
" \"price\": 25.0, " +
" \"message-types\": [" +
" {" +
" \"message-type\": \"UserParam{MESSAGE_TYPE_1}\", " +
" \"unit-price\": 1.1, " +
" \"nation\": \"UserParam{NATION_1}\"" +
" }, " +
" {" +
" \"message-type\": \"UserParam{MESSAGE_TYPE_2}\", " +
" \"unit-price\": 0.7, " +
" \"nation\": \"UserParam{NATION_2}\"" +
" }, " +
" {" +
" \"message-type\": \"UserParam{MESSAGE_TYPE_2}\", " +
" \"unit-price\": 1.5, " +
" \"nation\": \"UserParam{NATION_3}\"" +
" }" +
" ]" +
" }, " +
" {" +
" \"super-to-sub\": true, " +
" \"price\": 37.0, " +
" \"message-types\": [" +
" {" +
" \"message-type\": \"UserParam{MESSAGE_TYPE_1}\", " +
" \"unit-price\": 1.2" +
" }, " +
" {" +
" \"message-type\": \"UserParam{MESSAGE_TYPE_2}\", " +
" \"unit-price\": 0.8" +
" }" +
" ]" +
" }" +
" ]" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "purchases": [' .
' {' .
' "super-to-sub": true, ' .
' "price": 25.0, ' .
' "message-types": [' .
' {' .
' "message-type": "UserParam{MESSAGE_TYPE_1}", ' .
' "unit-price": 1.1, ' .
' "nation": "UserParam{NATION_1}"' .
' }, ' .
' {' .
' "message-type": "UserParam{MESSAGE_TYPE_2}", ' .
' "unit-price": 0.7, ' .
' "nation": "UserParam{NATION_2}"' .
' }, ' .
' {' .
' "message-type": "UserParam{MESSAGE_TYPE_2}", ' .
' "unit-price": 1.5, ' .
' "nation": "UserParam{NATION_3}"' .
' }' .
' ]' .
' }, ' .
' {' .
' "super-to-sub": true, ' .
' "price": 37.0, ' .
' "message-types": [' .
' {' .
' "message-type": "UserParam{MESSAGE_TYPE_1}", ' .
' "unit-price": 1.2' .
' }, ' .
' {' .
' "message-type": "UserParam{MESSAGE_TYPE_2}", ' .
' "unit-price": 0.8' .
' }' .
' ]' .
' }' .
' ]' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"purchases": [
{
"super-to-sub": true,
"price": 25.0,
"message-types": [
{
"message-type": "UserParam{MESSAGE_TYPE_1}",
"unit-price": 1.1,
"nation": "UserParam{NATION_1}"
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 0.7,
"nation": "UserParam{NATION_2}"
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 1.5,
"nation": "UserParam{NATION_3}"
}
]
},
{
"super-to-sub": true,
"price": 37.0,
"message-types": [
{
"message-type": "UserParam{MESSAGE_TYPE_1}",
"unit-price": 1.2
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 0.8
}
]
}
]
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase")
payload = {
"purchases": [
{
"super-to-sub": true,
"price": 25.0,
"message-types": [
{
"message-type": "UserParam{MESSAGE_TYPE_1}",
"unit-price": 1.1,
"nation": "UserParam{NATION_1}"
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 0.7,
"nation": "UserParam{NATION_2}"
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 1.5,
"nation": "UserParam{NATION_3}"
}
]
},
{
"super-to-sub": true,
"price": 37.0,
"message-types": [
{
"message-type": "UserParam{MESSAGE_TYPE_1}",
"unit-price": 1.2
},
{
"message-type": "UserParam{MESSAGE_TYPE_2}",
"unit-price": 0.8
}
]
}
]
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"purchases\": [" +
" {" +
" \"super-to-sub\": true, " +
" \"price\": 25.0, " +
" \"message-types\": [" +
" {" +
" \"message-type\": \"UserParam{MESSAGE_TYPE_1}\", " +
" \"unit-price\": 1.1, " +
" \"nation\": \"UserParam{NATION_1}\"" +
" }, " +
" {" +
" \"message-type\": \"UserParam{MESSAGE_TYPE_2}\", " +
" \"unit-price\": 0.7, " +
" \"nation\": \"UserParam{NATION_2}\"" +
" }, " +
" {" +
" \"message-type\": \"UserParam{MESSAGE_TYPE_2}\", " +
" \"unit-price\": 1.5, " +
" \"nation\": \"UserParam{NATION_3}\"" +
" }" +
" ]" +
" }, " +
" {" +
" \"super-to-sub\": true, " +
" \"price\": 37.0, " +
" \"message-types\": [" +
" {" +
" \"message-type\": \"UserParam{MESSAGE_TYPE_1}\", " +
" \"unit-price\": 1.2" +
" }, " +
" {" +
" \"message-type\": \"UserParam{MESSAGE_TYPE_2}\", " +
" \"unit-price\": 0.8" +
" }" +
" ]" +
" }" +
" ]" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase", "POST", payload);
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"purchases" => [
{
"super-to-sub" => true,
"price" => 25.0,
"message-types" => [
{
"message-type" => "UserParam{MESSAGE_TYPE_1}",
"unit-price" => 1.1,
"nation" => "UserParam{NATION_1}"
},
{
"message-type" => "UserParam{MESSAGE_TYPE_2}",
"unit-price" => 0.7,
"nation" => "UserParam{NATION_2}"
},
{
"message-type" => "UserParam{MESSAGE_TYPE_2}",
"unit-price" => 1.5,
"nation" => "UserParam{NATION_3}"
}
]
},
{
"super-to-sub" => true,
"price" => 37.0,
"message-types" => [
{
"message-type" => "UserParam{MESSAGE_TYPE_1}",
"unit-price" => 1.2
},
{
"message-type" => "UserParam{MESSAGE_TYPE_2}",
"unit-price" => 0.8
}
]
}
]
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
# The HTTP location header that points to the subaccount 'create purchase' URL:
'Location': '/subaccount/{subaccount_id}/purchase'
Creates one or more purchases for the given subaccount. Subaccount
credit-eat-mode
must be 2
. Caller must be a superaccount.
HTTP request
POST /API/v1.0/REST/subaccount/UserParam{subaccount}/purchase
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
subaccount_id | Int or String | The subaccount ID or Login | Yes | - |
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
purchases | List(Purchase) | The list of purchases to be created | Yes | - |
Purchase.message-types | List(MessageType) | The purchase’s message types | Yes | - |
Purchase.price | Float | The quantity of purchased credits | Yes | - |
MessageType.message-type | String | The message type (“GP” for Gold+) | Yes | - |
MessageType.unit-price | Float | The cost for the subaccount of a unit of the respective message-type | Yes | - |
MessageType.nation | String | The nation to which this price is bound, you must specify this paramenter only in case such nation is different from your account nation. Then nation must be specified in ISO-3166-1 format. If a nation is specified then the quality of the message must be high quality, otherwise the request will be rejected. This field is nullable since is not required | No | - |
Note that you only want to specify the nation if it is different from your account nation. For example, if you have got an Italian account and you want to give Italian credits, you don’t have to specify the nation.
Returns
Some errors may araise by the given call if you are specifying the nation. An invalid nation code may be passed and the backend will give a
- Value ‘
UserParam{NATION_1}
’ is not a valid iso 3166-1 value for parameter ‘nation’
or if the quality doesn’t match the highest quality possibile
- Value ‘
UserParam{MESSAGE_TYPE_1}
’ is not a valid quality: when specifying a nation allowed quality is GP
Code | Description |
---|---|
200 | Successful request. The HTTP location header that points to the subaccount ‘create purchase’ URL |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Delete a subaccount’s purchase
# Session Key example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase/UserParam{purchase_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase/UserParam{purchase_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.delete("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase/UserParam{purchase_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
print('Success!')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase/UserParam{purchase_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("DELETE");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("Success!");
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase/UserParam{purchase_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
echo('Success!');
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase/UserParam{purchase_id}',
method: 'DELETE',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
console.log('Success!');
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase/UserParam{purchase_id}")
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Delete.new(uri.request_uri)
request['Content-type'] = 'application/json'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
puts "Success!"
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase/UserParam{purchase_id}", "DELETE", new NameValueCollection());
Console.WriteLine("Success!");
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase/UserParam{purchase_id}";
my $req = HTTP::Request->new(DELETE => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
print "Success!";
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{"result":"OK"}
Deletes a purchase of the given subaccount. Caller must be a
superaccount, and the Subaccount’s credit-eat-mode
should be 2
.
HTTP request
DELETE /API/v1.0/REST/subaccount/UserParam{subaccount_id}/purchase/UserParam{purchase_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
subaccount_id | Int or String | The subaccount ID or Login | Yes | - |
purchase_id | Int | The purchase ID | Yes | - |
Returns
Code | Description |
---|---|
200 | Successful request, purchase successfully deleted |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Subaccount Profile API
The Subaccount Profile API is used to deal with subaccount profiles entries of a given account bound to the user.
Create a subaccount profile
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"name": "creation test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4ERSngBaas466fasfdqQK-sPYG32341PqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": false,
"enabledServices": [
"pages",
"sms",
"smsadv",
"richsms",
"email",
"rcp",
"sr"
],
"enabledSMSQualities": [
"GP",
"TI",
"SI",
"AD"
]
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"name": "creation test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4ERSngBaas466fasfdqQK-sPYG32341PqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": false,
"enabledServices": [
"pages",
"sms",
"smsadv",
"richsms",
"email",
"rcp",
"sr"
],
"enabledSMSQualities": [
"GP",
"TI",
"SI",
"AD"
]
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"name": "creation test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4ERSngBaas466fasfdqQK-sPYG32341PqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": false,
"enabledServices": [
"pages",
"sms",
"smsadv",
"richsms",
"email",
"rcp",
"sr"
],
"enabledSMSQualities": [
"GP",
"TI",
"SI",
"AD"
]
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"name\": \"creation test\", " +
" \"isDefault\": false, " +
" \"numSubaccount\": 0, " +
" \"sharedGroups\": [" +
" \"-4ERSngBaas466fasfdqQK-sPYG32341PqVx\"" +
" ], " +
" \"sharedTemplates\": [" +
" 30" +
" ], " +
" \"sharedBlacklists\": false, " +
" \"enabledServices\": [" +
" \"pages\", " +
" \"sms\", " +
" \"smsadv\", " +
" \"richsms\", " +
" \"email\", " +
" \"rcp\", " +
" \"sr\"" +
" ], " +
" \"enabledSMSQualities\": [" +
" \"GP\", " +
" \"TI\", " +
" \"SI\", " +
" \"AD\"" +
" ]" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "name": "creation test", ' .
' "isDefault": false, ' .
' "numSubaccount": 0, ' .
' "sharedGroups": [' .
' "-4ERSngBaas466fasfdqQK-sPYG32341PqVx"' .
' ], ' .
' "sharedTemplates": [' .
' 30' .
' ], ' .
' "sharedBlacklists": false, ' .
' "enabledServices": [' .
' "pages", ' .
' "sms", ' .
' "smsadv", ' .
' "richsms", ' .
' "email", ' .
' "rcp", ' .
' "sr"' .
' ], ' .
' "enabledSMSQualities": [' .
' "GP", ' .
' "TI", ' .
' "SI", ' .
' "AD"' .
' ]' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"name": "creation test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4ERSngBaas466fasfdqQK-sPYG32341PqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": false,
"enabledServices": [
"pages",
"sms",
"smsadv",
"richsms",
"email",
"rcp",
"sr"
],
"enabledSMSQualities": [
"GP",
"TI",
"SI",
"AD"
]
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile")
payload = {
"name": "creation test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4ERSngBaas466fasfdqQK-sPYG32341PqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": false,
"enabledServices": [
"pages",
"sms",
"smsadv",
"richsms",
"email",
"rcp",
"sr"
],
"enabledSMSQualities": [
"GP",
"TI",
"SI",
"AD"
]
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"name\": \"creation test\", " +
" \"isDefault\": false, " +
" \"numSubaccount\": 0, " +
" \"sharedGroups\": [" +
" \"-4ERSngBaas466fasfdqQK-sPYG32341PqVx\"" +
" ], " +
" \"sharedTemplates\": [" +
" 30" +
" ], " +
" \"sharedBlacklists\": false, " +
" \"enabledServices\": [" +
" \"pages\", " +
" \"sms\", " +
" \"smsadv\", " +
" \"richsms\", " +
" \"email\", " +
" \"rcp\", " +
" \"sr\"" +
" ], " +
" \"enabledSMSQualities\": [" +
" \"GP\", " +
" \"TI\", " +
" \"SI\", " +
" \"AD\"" +
" ]" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile", "POST", payload);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/profile";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"name" => "creation test",
"isDefault" => false,
"numSubaccount" => 0,
"sharedGroups" => [
"-4ERSngBaas466fasfdqQK-sPYG32341PqVx"
],
"sharedTemplates" => [
30
],
"sharedBlacklists" => false,
"enabledServices" => [
"pages",
"sms",
"smsadv",
"richsms",
"email",
"rcp",
"sr"
],
"enabledSMSQualities" => [
"GP",
"TI",
"SI",
"AD"
]
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On creation succes, the above is returned:
{
"idSubaccountProfile":91213,
"name":"creation test",
"enabledServices":[
"pages",
"sms",
"smsadv",
"richsms",
"email",
"rcp",
"sr"
],
"enabledSMSQualities":[
"GP",
"TI",
"SI",
"AD"
],
"numSubaccount":0,
"sharedGroups":[
{
"id":"-4ERSngBaas466fasfdqQK-sPYG32341PqVx",
"name":"Test",
"description":"",
"groupType":0,
"totalContactsCount":0,
"sharingInfo":{
"idSharing":41234,
"idParentSharing":0,
"idUserSharing":4123,
"idUserResourceOwner":4123,
"idSubaccountProfile":91213
},
"emailContactsCount":0
}
],
"sharedTemplates":[
{
"idTemplate":30,
"encoding":"GSM",
"name":"Model 02",
"text":"This is model for api docs",
"sender":null,
"richUrl":null,
"idPage":null,
"sharingInfo":{
"idSharing":454123,
"idParentSharing":0,
"idUserSharing":4123,
"idUserResourceOwner":4123,
"idSubaccountProfile":91213
}
}
],
"sharedBlacklists":[
{
"userOwnerId":4123,
"sharingInfo":{
"idSharing":46,
"idParentSharing":0,
"idUserSharing":4123,
"idUserResourceOwner":4123,
"idSubaccountProfile":91213
}
}
],
"isDefault":false
}
Creates a new Subaccount profile.
HTTP request
POST /API/v1.0/REST/subaccount/profile
Body fields
The body must contain a Json with the following content:
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
name | String | The name of the subaccount | Yes | |
isDefault | boolean | Tell whether or not this must be set as default account | Yes | |
numSubaccount | number | Limits the number of subaccount that can be created | Yes | |
sharedGroups | List(String) | Ids of the groups to be shared with the created subaccount. Can be an empty list | Yes | |
sharedTemplates | List(number) | Ids of the templates to share with the created subaccount. Can be an empty list | Yes | |
sharedBlacklists | boolean | Tell whether or not to share the owner and the owner’ shared blacklists | Yes | |
enabledServices | List(String) | The list of services to enable | Yes | |
enabledSMSQualities | List(String) | The list of sms qualities to enable | Yes |
Returns
Code | Description |
---|---|
200 | Successful request |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Update a subaccount profile
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"idSubaccountProfile": 92789,
"name": "test-test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4789ERSngBqQK-sPYGPqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": true,
"enabledServices": [
"sms",
"pages",
"richsms"
],
"enabledSMSQualities": [
"GP",
"TI"
]
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"idSubaccountProfile": 92789,
"name": "test-test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4789ERSngBqQK-sPYGPqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": true,
"enabledServices": [
"sms",
"pages",
"richsms"
],
"enabledSMSQualities": [
"GP",
"TI"
]
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"idSubaccountProfile": 92789,
"name": "test-test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4789ERSngBqQK-sPYGPqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": true,
"enabledServices": [
"sms",
"pages",
"richsms"
],
"enabledSMSQualities": [
"GP",
"TI"
]
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"idSubaccountProfile\": 92789, " +
" \"name\": \"test-test\", " +
" \"isDefault\": false, " +
" \"numSubaccount\": 0, " +
" \"sharedGroups\": [" +
" \"-4789ERSngBqQK-sPYGPqVx\"" +
" ], " +
" \"sharedTemplates\": [" +
" 30" +
" ], " +
" \"sharedBlacklists\": true, " +
" \"enabledServices\": [" +
" \"sms\", " +
" \"pages\", " +
" \"richsms\"" +
" ], " +
" \"enabledSMSQualities\": [" +
" \"GP\", " +
" \"TI\"" +
" ]" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "idSubaccountProfile": 92789, ' .
' "name": "test-test", ' .
' "isDefault": false, ' .
' "numSubaccount": 0, ' .
' "sharedGroups": [' .
' "-4789ERSngBqQK-sPYGPqVx"' .
' ], ' .
' "sharedTemplates": [' .
' 30' .
' ], ' .
' "sharedBlacklists": true, ' .
' "enabledServices": [' .
' "sms", ' .
' "pages", ' .
' "richsms"' .
' ], ' .
' "enabledSMSQualities": [' .
' "GP", ' .
' "TI"' .
' ]' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"idSubaccountProfile": 92789,
"name": "test-test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4789ERSngBqQK-sPYGPqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": true,
"enabledServices": [
"sms",
"pages",
"richsms"
],
"enabledSMSQualities": [
"GP",
"TI"
]
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}")
payload = {
"idSubaccountProfile": 92789,
"name": "test-test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4789ERSngBqQK-sPYGPqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": true,
"enabledServices": [
"sms",
"pages",
"richsms"
],
"enabledSMSQualities": [
"GP",
"TI"
]
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"idSubaccountProfile\": 92789, " +
" \"name\": \"test-test\", " +
" \"isDefault\": false, " +
" \"numSubaccount\": 0, " +
" \"sharedGroups\": [" +
" \"-4789ERSngBqQK-sPYGPqVx\"" +
" ], " +
" \"sharedTemplates\": [" +
" 30" +
" ], " +
" \"sharedBlacklists\": true, " +
" \"enabledServices\": [" +
" \"sms\", " +
" \"pages\", " +
" \"richsms\"" +
" ], " +
" \"enabledSMSQualities\": [" +
" \"GP\", " +
" \"TI\"" +
" ]" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}", "POST", payload);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"idSubaccountProfile" => 92789,
"name" => "test-test",
"isDefault" => false,
"numSubaccount" => 0,
"sharedGroups" => [
"-4789ERSngBqQK-sPYGPqVx"
],
"sharedTemplates" => [
30
],
"sharedBlacklists" => true,
"enabledServices" => [
"sms",
"pages",
"richsms"
],
"enabledSMSQualities" => [
"GP",
"TI"
]
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On update succes, the above is returned:
{
"idSubaccountProfile":92789,
"name":"test-test",
"enabledServices":[
"sms",
"pages",
"richsms"
],
"enabledSMSQualities":[
"GP",
"TI"
],
"numSubaccount":0,
"sharedGroups":[
{
"id":"-4789ERSngBqQK-sPYGPqVx",
"name":"A-789",
"description":"",
"groupType":0,
"totalContactsCount":0,
"sharingInfo":{
"idSharing":41789,
"idParentSharing":0,
"idUserSharing":4789,
"idUserResourceOwner":4789,
"idSubaccountProfile":92789
},
"emailContactsCount":0
}
],
"sharedTemplates":[
{
"idTemplate":30,
"encoding":"GSM-789",
"name":"Modello 02789",
"text":"This is 789 model",
"sender":null,
"richUrl":null,
"idPage":null,
"sharingInfo":{
"idSharing":42789,
"idParentSharing":0,
"idUserSharing":4789,
"idUserResourceOwner":4789,
"idSubaccountProfile":92789
}
}
],
"sharedBlacklists":[
{
"userOwnerId":4789,
"sharingInfo":{
"idSharing":43789,
"idParentSharing":0,
"idUserSharing":4789,
"idUserResourceOwner":4789,
"idSubaccountProfile":92789
}
}
],
"isDefault":false
}
Updates the given Subaccount profile.
HTTP request
POST /API/v1.0/REST/subaccount/profile/UserParam{profile_id}
Body fields
The body must contain a Json with the following content:
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
name | String | The name of the subaccount | Yes | |
isDefault | boolean | Tell whether or not this must be set as default account | Yes | |
numSubaccount | number | Limits the number of subaccount that can be created | Yes | |
sharedGroups | List(String) | Ids of the groups to be shared with the created subaccount. Can be an empty list | Yes | |
sharedTemplates | List(number) | Ids of the templates to share with the created subaccount. Can be an empty list | Yes | |
sharedBlacklists | boolean | Tell whether or not to share the owner and the owner’ shared blacklists | Yes | |
enabledServices | List(String) | The list of services to enable | Yes | |
enabledSMSQualities | List(String) | The list of sms qualities to enable | Yes |
Returns
Code | Description |
---|---|
200 | Successful request |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get all subaccount profiles
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/profile";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
[
{
"idSubaccountProfile":15123,
"name":"default",
"enabledServices":[
"sms",
"email",
"sr"
],
"enabledSMSQualities":[
"GP",
"SI"
],
"numSubaccount":33123,
"sharedGroups":[
{
"id":"e4CeG3gBq123QK-sPYG355x",
"name":"test",
"description":"",
"groupType":0,
"totalContactsCount":0,
"sharingInfo":{
"idSharing":9123,
"idParentSharing":0,
"idUserSharing":4123,
"idUserResourceOwner":4123,
"idSubaccountProfile":15123
},
"emailContactsCount":0
}
],
"sharedTemplates":[
{
"idTemplate":29123,
"encoding":"GSM",
"name":"Model 01123",
"text":"Model 123123",
"sender":null,
"richUrl":null,
"idPage":null,
"sharingInfo":{
"idSharing":10123,
"idParentSharing":0,
"idUserSharing":4123,
"idUserResourceOwner":4123,
"idSubaccountProfile":15123
}
}
],
"sharedBlacklists":[
],
"isDefault":true
},
{
"idSubaccountProfile":34123,
"name":"Name 123",
"enabledServices":[
"sms",
"email"
],
"enabledSMSQualities":[
"GP",
"TI",
"SI",
"AD"
],
"numSubaccount":2123,
"sharedGroups":[
{
"id":"doCeG3gB123qQK-sPYGzp5Q",
"name":"Name 2-123",
"description":"",
"groupType":0,
"totalContactsCount":0,
"sharingInfo":{
"idSharing":5123,
"idParentSharing":0,
"idUserSharing":4123,
"idUserResourceOwner":4123,
"idSubaccountProfile":34123
},
"emailContactsCount":0
}
],
"sharedTemplates":[
],
"sharedBlacklists":[
],
"isDefault":false
}
]
Returns the list of subaccount profiles.
HTTP request
GET /API/v1.0/REST/subaccount/profile
Returns
Code | Description |
---|---|
200 | The list of the user’s Subaccount profiles |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Get a specific subaccount profile
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"idSubaccountProfile":154321,
"name":"default",
"enabledServices":[
"sms",
"email",
"sr"
],
"enabledSMSQualities":[
"GP",
"SI"
],
"numSubaccount":0,
"sharedGroups":[
{
"id":"e4CeG3g4321BqQK-sPYG355x",
"name":"Example name",
"description":"",
"groupType":0,
"totalContactsCount":0,
"sharingInfo":{
"idSharing":94321,
"idParentSharing":0,
"idUserSharing":44321,
"idUserResourceOwner":44321,
"idSubaccountProfile":154321
},
"emailContactsCount":0
}
],
"sharedTemplates":[
{
"idTemplate":294321,
"encoding":"GSM",
"name":"Model 4321",
"text":"Text for model 4321 test",
"sender":null,
"richUrl":null,
"idPage":null,
"sharingInfo":{
"idSharing":104321,
"idParentSharing":0,
"idUserSharing":44321,
"idUserResourceOwner":44321,
"idSubaccountProfile":154321
}
}
],
"sharedBlacklists":[
],
"isDefault":true
}
Returns the data of the given SubaccountProfile ID.
HTTP request
GET /API/v1.0/REST/subaccount/profile/UserParam{profile_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
profile_id | Int | The Profile ID | Yes | - |
Returns
Code | Description |
---|---|
200 | The requested Subaccount Profile data |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The profile was not found |
Get activable services
# Session Key example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XGET 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices',
method: 'GET',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices")
# 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'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String response = wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices");
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices";
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
[
"sms",
"email",
"sr",
"pages",
"richsms",
"rcp",
"smsadv"
]
Returns the activable services for the querying account.
HTTP request
GET /API/v1.0/REST/subaccount/profile/activableServices
Returns
Code | Description |
---|---|
200 | A string list of the activable services |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
Remove a subaccount profile
# Session Key example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}'
# Access token example
curl -XDELETE 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
r = requests.delete("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}", headers=headers)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("DELETE");
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}',
method: 'DELETE',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}")
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Delete.new(uri.request_uri)
request['Content-type'] = 'application/json'
request['user_key'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}", "DELETE", new NameValueCollection());
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/UserParam{profile_id}";
my $req = HTTP::Request->new(DELETE => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{}
Deletes the given Subaccount Profile.
HTTP request
DELETE /API/v1.0/REST/subaccount/profile/UserParam{profile_id}
Parameters
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
profile_id | Int | The Profile ID | Yes | - |
Returns
Code | Description |
---|---|
200 | Subaccount profile successfully deleted |
400 | Other errors, details are in the body |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The p was not found |
Two Factor Authentication API
This is the part of the API that provides the Two Factor Authentication. The flow of 2FA is:
The user specifies their number in your App.
Your app sends a 2FA request via API.
The platform sends a text message to the specified recipient.
User receives the PIN via text message.
User enters the PIN in your App.
Your app sends the 2FA verify via API and receives the authorization or an invalid pin error.
The text message is sent with the highest quality on a preferred route, to guarantee a quick delivery.
Request a 2FA pin
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/2fa/request' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"recipient": "+443471234567"
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/2fa/request' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"recipient": "+443471234567"
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"recipient": "+443471234567"
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/2fa/request", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/2fa/request");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"recipient\": \"+443471234567\"" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "recipient": "+443471234567"' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/2fa/request');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/2fa/request',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"recipient": "+443471234567"
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/2fa/request")
payload = {
"recipient": "+443471234567"
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"recipient\": \"+443471234567\"" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/2fa/request", "POST", payload);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/2fa/request";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"recipient" => "+443471234567"
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"status": "OK"
}
On failure, the above command returns the following response:
{
"status": "ERROR",
"error": "Error cause"
}
Request a Two Factor Authentication via text message. This method generates a pin and sends it via text message to the user.
HTTP request
POST /API/v1.0/REST/2fa/request
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
recipient | String | The phone number of the user. The format must be +441234567890 or 00441234567890 | Yes | - |
senderName | String | The sender name or number for the text message | No | Preferred Sender Name |
expiry | Integer | The expiration time of the PIN, in minutes | No | 60 |
messageBody | String | The message body. PIN position in the text can be specified using the %PIN% placeholder. If the placeholder is not provided the pin will be added at the end of message body. | No | A default message body per language. |
Returns
Code | Description |
---|---|
200 | pin has been successfully sent via text message. |
400 | [Bad request] Invalid recipient, senderName, expiry, or sending errors like not enough credit. |
401 | [Unauthorized] User_key, Token or Session_key are invalid or not provided |
404 | [Not found] The User_key was not found |
Verify a 2FA pin
# Session Key example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/2fa/verify' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Session_key: UserParam{session_key}' -d'
{
"recipient": "+443471234567",
"pin": "12345"
}
'
# Access token example
curl -XPOST 'https://api.textanywhere.com/API/v1.0/REST/2fa/verify' -H 'Content-Type: application/json' \
-H 'user_key: UserParam{user_key}' -H 'Access_token: UserParam{access_token}' -d'
{
"recipient": "+443471234567",
"pin": "12345"
}
'
# pip install requests
import requests
import json
from requests.auth import HTTPBasicAuth
# Use this when using Session Key authentication
headers = { 'user_key': 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}', 'Content-type' : 'application/json' }
# When using Access Token authentication, use this instead:
# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }
payload = """{
"recipient": "+443471234567",
"pin": "12345"
}"""
r = requests.post("https://api.textanywhere.com/API/v1.0/REST/2fa/verify", headers=headers, data=payload)
if r.status_code != 200:
print("Error! http code: " + str(r.status_code) + ", body message: " + str(r.content))
else:
response = r.text
obj = json.loads(response)
print(unicode(obj))
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.textanywhere.com/API/v1.0/REST/2fa/verify");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("user_key", "UserParam{user_key}");
// Use this when using Session Key authentication
conn.setRequestProperty("Session_key", "UserParam{session_key}");
// When using Access Token authentication, use this instead:
// conn.setRequestProperty("Access_token", "UserParam{access_token}");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoOutput(true);
String payload = "{" +
" \"recipient\": \"+443471234567\", " +
" \"pin\": \"12345\"" +
"}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
// Print the possible error contained in body response
String error = "";
String output;
BufferedReader errorbuffer = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
while ((output = errorbuffer.readLine()) != null) {
error += output;
}
System.out.println("Error! HTTP error code : " + conn.getResponseCode() +
", Body message : " + error);
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;
}
// You can parse the response using Google GSON or similar.
// MyObject should be a class that reflect the JSON
// structure of the response
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyObject responseObj = gson.fromJson(response, MyObject.class);
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<?php
$payload = '{' .
' "recipient": "+443471234567", ' .
' "pin": "12345"' .
'}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.textanywhere.com/API/v1.0/REST/2fa/verify');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'user_key: UserParam{user_key}',
// Use this when using session key authentication
'Session_key: UserParam{session_key}',
// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200) {
echo('Error! http code: ' . $info['http_code'] . ', body message: ' . $response);
}
else {
$obj = json_decode($response);
print_r($obj);
}
?>
// Uses https://github.com/request/request
// npm install [-g] request
var request = require('request');
request({
url: 'https://api.textanywhere.com/API/v1.0/REST/2fa/verify',
method: 'POST',
headers: { 'user_key' : 'UserParam{user_key}', 'Session_key' : 'UserParam{session_key}' },
json: true,
body: {
"recipient": "+443471234567",
"pin": "12345"
},
callback: function (error, responseMeta, response) {
if (!error && responseMeta.statusCode == 200) {
}
else {
console.log('Error! http code: ' + responseMeta.statusCode + ', body message: ' + response)
}
}
});
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.textanywhere.com/API/v1.0/REST/2fa/verify")
payload = {
"recipient": "+443471234567",
"pin": "12345"
}
# 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'] = 'UserParam{user_key}'
request['Session_key'] = 'UserParam{session_key}'
request.body = payload.to_json
# Send the request
responseData = http.request(request)
if responseData.code == "200"
response = responseData.body
obj = JSON.parse(response)
puts obj
else
puts "Error! http code: " + responseData.code + ", body message: " + responseData.body
end
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Specialized;
// 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
{
static void Main(string[] args)
{
using (var wb = new WebClient())
{
// Setting the encoding is required when sending UTF8 characters!
wb.Encoding = System.Text.Encoding.UTF8;
try {
wb.Headers.Set(HttpRequestHeader.ContentType, "application/json");
wb.Headers.Add("user_key", "UserParam{user_key}");
wb.Headers.Add("Session_key", "UserParam{session_key}");
String payload = "{" +
" \"recipient\": \"+443471234567\", " +
" \"pin\": \"12345\"" +
"}";
String response = wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/2fa/verify", "POST", payload);
dynamic obj = JsonConvert.DeserializeObject(response);
Console.WriteLine(obj);
} catch (WebException ex) {
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
var errorResponse = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Error!, http code: " + statusCode + ", body message: ");
Console.WriteLine(errorResponse);
}
}
}
}
}
#!/usr/bin/env perl
use warnings;
use strict;
use LWP::UserAgent;
# Install using Cpan: "cpan JSON URI"
use JSON;
use URI::Escape;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://api.textanywhere.com/API/v1.0/REST/2fa/verify";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('Content_type' => 'application/json');
# 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(':user_key' => $auth->[0],
':Session_key' => $auth->[1]);
my $payload = {
"recipient" => "+443471234567",
"pin" => "12345"
};
$req->content(to_json($payload));
my $resp = $ua->request($req);
if ($resp->is_success && $resp->code == 200) {
my $response = $resp->decoded_content;
my $obj = from_json($response);
} else {
my $error = $resp->decoded_content;
my $code = $resp->code;
print "Error!, http code: $code, body message: $error ";
}
On success, the above command returns the following response:
{
"status": "OK"
}
On wrong pin, the above command returns the following response:
{
"status": "ERROR",
"error": "Wrong pin",
"triesRemaining": 2
}
On failure, the above command returns the following response:
{
"status": "ERROR",
"error": "Error cause"
}
Verify that the pin provided by the user is valid.
HTTP request
POST /API/v1.0/REST/2fa/verify
Body fields
Parameter | Type | Description | Required | Default |
---|---|---|---|---|
recipient | String | The phone number of the user. The format must be +441234567890 or 00441234567890 | Yes | - |
pin | String | The pin inserted by the user | Yes | - |
Returns
Code | Description |
---|---|
200 | If status is OK the 2FA is valid, if status is ERROR the passed pin is wrong and the response includes the number of tries remaining. |
400 | [Bad request] No recipient, No pin, No user_key, Max retry exceeded, Expired, Already verified, Unknown error |
403 | [Unauthorized] Session_key invalid/absent, Unauthorized user_key/Session_key pair |
404 | [Not found] No 2FA transaction found for this user or recipient |