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