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 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.
importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.net.HttpURLConnection;importjava.net.URL;importjava.util.ArrayList;importjava.util.Date;importjava.util.List;// This example requires Gson configured in the build path (for JSON support):// https://github.com/google/gsonimportcom.google.gson.Gson;importcom.google.gson.GsonBuilder;publicclassMain{publicstaticfinalStringBASEURL="https://api.textanywhere.com/API/v1.0/REST/";publicstaticfinalStringMESSAGE_HIGH_QUALITY="GP";publicstaticfinalStringMESSAGE_MEDIUM_QUALITY="GS";publicstaticvoidmain(String[]args){try{String[]authKeys=login("my_registration_email","my_password");SendSMSRequestsendSMS=newSendSMSRequest();sendSMS.setMessage("Hello world!");sendSMS.setMessageType(MESSAGE_HIGH_QUALITY);sendSMS.addRecipient("+44123456789");// Send it in 5 minutes!sendSMS.setScheduledDeliveryTime(newDate(System.currentTimeMillis()+(60000L*5L)));sendSMS(authKeys,sendSMS);}catch(Exceptione){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.
*/publicstaticclassSendSMSRequest{/** The message body */privateStringmessage;/** The message type */privateStringmessage_type=MESSAGE_HIGH_QUALITY;/** Should the API return the remaining credits? */privatebooleanreturnCredits=false;/** The list of recipients */privateList<String>recipient=newArrayList<>();/** The sender Alias (TPOA) */privateStringsender=null;/** Postpone the SMS message sending to the specified date */privateDatescheduled_delivery_time=null;publicStringgetMessage(){returnmessage;}publicvoidsetMessage(Stringmessage){this.message=message;}publicStringgetMessageType(){returnmessage_type;}publicvoidsetMessageType(StringmessageType){this.message_type=messageType;}publicbooleanisReturnCredits(){returnreturnCredits;}publicvoidsetReturnCredits(booleanreturnCredits){this.returnCredits=returnCredits;}publicList<String>getRecipient(){returnrecipient;}publicStringgetSender(){returnsender;}publicvoidsetSender(Stringsender){this.sender=sender;}publicDategetScheduledDeliveryTime(){returnscheduled_delivery_time;}publicvoidsetScheduledDeliveryTime(Datescheduled_delivery_time){this.scheduled_delivery_time=scheduled_delivery_time;}publicvoidaddRecipient(Stringrecipient){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
*/publicstaticclassSendSMSResponse{privateStringresult;privateStringorder_id;privateinttotal_sent;privateintremaining_credits;privateStringinternal_order_id;publicStringgetResult(){returnresult;}publicStringgetOrderId(){returnorder_id;}publicintgetTotalSent(){returntotal_sent;}publicintgetRemainingCredits(){returnremaining_credits;}publicStringgetInternalOrderId(){returninternal_order_id;}publicbooleanisValid(){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
*/privatestaticString[]login(Stringusername,Stringpassword)throwsIOException{URLurl=newURL(BASEURL+"/login?username="+username+"&password="+password);HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestMethod("GET");if(conn.getResponseCode()!=200){thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;while((output=br.readLine())!=null){response+=output;}conn.disconnect();String[]parts=response.split(";");returnparts;}/**
* 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
*/privatestaticbooleansendSMS(String[]authKeys,SendSMSRequestsendSMS)throwsIOException{GsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();URLurl=newURL(BASEURL+"/sms");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();// Sending an SMS requires authenticationconn.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);Stringpayload=gson.toJson(sendSMS);OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=201){thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;while((output=br.readLine())!=null){response+=output;}conn.disconnect();SendSMSResponseresponseObj=gson.fromJson(response,SendSMSResponse.class);returnresponseObj.isValid();}}
<?phpdefine("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
*/functionlogin($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){returnnull;}returnexplode(";",$response);}/**
* Sends an SMS message
*/functionsendSMS($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){returnnull;}returnjson_decode($response);}$auth=login('my_registration_email','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 requestsimportrequestsimportjsonimportsysimportdatetimeBASEURL="https://api.textanywhere.com/API/v1.0/REST/"MESSAGE_HIGH_QUALITY="GP"MESSAGE_MEDIUM_QUALITY="GS"defjson_serial(obj):"""JSON serializer for objects not serializable by default json code"""ifisinstance(obj,datetime.datetime):serial=obj.isoformat()returnserialraiseTypeError("Type not serializable")deflogin(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))ifr.status_code!=200:returnNoneuser_key,session_key=r.text.split(';')returnuser_key,session_keydefsendSMS(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))ifr.status_code!=201:returnNonereturnjson.loads(r.text)if__name__=="__main__":auth=login("my_registration_email","my_password")ifnotauth: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))})ifsentSMS['result']=="OK":print("SMS sent!")
varBASEURL='https://api.textanywhere.com/API/v1.0/REST/';varMESSAGE_HIGH_QUALITY="GP";varMESSAGE_MEDIUM_QUALITY="GS";varrequest=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.
*/functionlogin(username,password,callback){request({url:BASEURL+'login?username='+username+'&password='+password,method:'GET',callback:function(error,responseMeta,response){if(!error&&responseMeta.statusCode==200){varauth=response.split(';');callback(error,{user_key:auth[0],session_key:auth[1]});}else{callback(error);}}});}/**
* Sends an SMS message
*/functionsendSMS(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);}}});}varsmsData={"returnCredits":true,"recipient":["+443471234567","+443471234568"],"scheduled_delivery_time":"20171223101010","message":"Hello world!","message_type":MESSAGE_HIGH_QUALITY}login('my_registration_email','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)deflogin(username,password)uri=URI.parse(BASEURL+"login?username="+username+"&password="+password)# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"returnresponseData.body.split(';')endreturnNoneend# Sends an SMSdefsendSMS(auth,sendSMS)uri=URI.parse(BASEURL+"sms")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=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 requestresponseData=http.request(request)ifresponseData.code=="201"returnJSON.parse(responseData.body)elsereturnNoneendend##################### Mainauth=login('my_registration_email','my_password')ifnotauthputs"Unable to login"elseresponse=sendSMS(auth,{"returnCredits":true,"recipient":["+443471234567","+443471234568"],"message":"Hello world!","message_type":MESSAGE_HIGH_QUALITY,})ifresponse['result']=='OK'puts"SMS Sent!"elseputs"An error occurred"endend
usingSystem;usingSystem.Text;usingSystem.Net;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{publicclassProgram{publicstaticStringBASEURL="https://api.textanywhere.com/API/v1.0/REST/";publicstaticStringMESSAGE_HIGH_QUALITY="GP";publicstaticStringMESSAGE_MEDIUM_QUALITY="GS";publicstaticvoidMain(string[]args){String[]auth=authenticate("my_registration_email","my_password");SendSMSsendSMSRequest=newSendSMS();sendSMSRequest.message="Hello World!";sendSMSRequest.message_type=MESSAGE_HIGH_QUALITY;sendSMSRequest.recipient=newString[]{"+44349123456789"};// Send the SMS message at the given date (Optional)sendSMSRequest.scheduled_delivery_time=newDateTime(2017,8,18,13,31,00);SMSSentsmsSent=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)
*/staticString[]authenticate(Stringusername,Stringpassword){String[]auth=null;using(varwb=newWebClient()){varresponse=wb.DownloadString(BASEURL+"login?username="+username+"&password="+password);auth=response.Split(';');}returnauth;}/**
* Sends an SMS
*/staticSMSSentsendSMS(String[]auth,SendSMSsendSMS){using(varwb=newWebClient()){// 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]);Stringjson=JsonConvert.SerializeObject(sendSMS);varsentSMSBody=wb.UploadString(BASEURL+"sms","POST",json);SMSSentsentSMSResponse=JsonConvert.DeserializeObject<SMSSent>(sentSMSBody);returnsentSMSResponse;}}}/**
* 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.
*/classSendSMS{/** The message body */publicStringmessage;/** The message type */publicStringmessage_type;/** The sender Alias (TPOA) */publicStringsender;/** Postpone the SMS message sending to the specified date */publicDateTime?scheduled_delivery_time;/** The list of recipients */publicString[]recipient;/** Should the API return the remaining credits? */publicBooleanreturnCredits=false;}/**
* This class represents the API Response. It is automatically created starting
* from the JSON object returned by the server, using GSon
*/classSMSSent{/** The result of the SMS message sending */publicStringresult;/** The order ID of the SMS message sending */publicStringorder_id;/** The actual number of sent SMS messages */publicinttotal_sent;/** The remaining credits */publicintremaining_credits;}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useLWP::UserAgent;useconstantBASEURL=>"https://api.textanywhere.com/API/v1.0/REST/";useconstantMESSAGE_HIGH_QUALITY=>"GP";useconstantMESSAGE_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){returnfrom_json($resp->decoded_content);}}my$ua=LWP::UserAgent->new;my$auth=authenticate($ua,"my_registration_email","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 my_registration_email and 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.
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/login");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();// Encode username and password as Basic Authentication standardStringencoding=Base64.getEncoder().encodeToString(("my_registration_email:my_password").getBytes("UTF-8"));conn.setRequestProperty("Authorization","Basic "+encoding);conn.setRequestMethod("GET");if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;while((output=br.readLine())!=null){response+=output;}String[]parts=response.split(";");Stringuser_key=parts[0];Stringsession_key=parts[1];System.out.println("user_key: "+user_key);System.out.println("Session_key: "+session_key);conn.disconnect();}catch(Exceptione){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,'my_registration_email: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]);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/login")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request.basic_auth'my_registration_email','my_password'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyuser_key,session_key=response.split(';')puts"user_key: "+user_keyputs"Session_key: "+session_keyelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// Setting the encoding is required when sending UTF8 characters!wb.Encoding=System.Text.Encoding.UTF8;try{stringencoded=System.Convert.ToBase64String(Encoding.GetEncoding("UTF-8").GetBytes(UserParam{my_registration_email}+":"+UserParam{my_password}));wb.Headers.Add("Authorization","Basic "+encoded);Stringresponse=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(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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:USER_KEY
Session_key:SESSION_KEY
Where USER_KEY and 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)}"
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/token");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();// Encode username and password as Basic Authentication standardStringencoding=Base64.getEncoder().encodeToString(("my_registration_email:my_password").getBytes("UTF-8"));conn.setRequestProperty("Authorization","Basic "+encoding);conn.setRequestMethod("GET");if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;while((output=br.readLine())!=null){response+=output;}String[]parts=response.split(";");Stringuser_key=parts[0];Stringaccess_token=parts[1];System.out.println("user_key: "+user_key);System.out.println("Access_token: "+access_token);conn.disconnect();}catch(Exceptione){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,'my_registration_email: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]);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/token")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request.basic_auth'my_registration_email','my_password'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyuser_key,access_token=response.split(';')puts"user_key: "+user_keyputs"Access_token: "+access_tokenelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// Setting the encoding is required when sending UTF8 characters!wb.Encoding=System.Text.Encoding.UTF8;try{stringencoded=System.Convert.ToBase64String(Encoding.GetEncoding("UTF-8").GetBytes(UserParam{my_registration_email}+":"+UserParam{my_password}));wb.Headers.Add("Authorization","Basic "+encoded);Stringresponse=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(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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:USER_KEY
Access_token:ACCESS_TOKEN
Where USER_KEY and 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)
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textprint(response)
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/dashboard");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;while((output=br.readLine())!=null){response+=output;}System.out.println(response);conn.disconnect();}catch(Exceptione){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: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/dashboard")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputsresponseelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/dashboard");Console.WriteLine(response);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textprint("Is session valid: "+str(response=="true"))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/checksession");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;while((output=br.readLine())!=null){response+=output;}System.out.println("Is session valid: "+("true".equals(response)));conn.disconnect();}catch(Exceptione){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: user_key',// Use this when using session key authentication
'Session_key: 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"));}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/checksession")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Is session valid "+responseelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/checksession");Console.WriteLine("Is session valid: "+response);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textprint("Password changed: "+str(response=="true"))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="UserParam{new_password}"");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;while((output=br.readLine())!=null){response+=output;}System.out.println("Password changed: "+("true".equals(response)));conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="new_password"');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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"));}?>
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 objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Password changed "+responseelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/pwdreset?password="UserParam{new_password}"","POST",null);Console.WriteLine("Password changed: "+response);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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": "new_password"
}"""r=requests.post("https://api.textanywhere.com/API/v1.0/REST/pwdreset/api",headers=headers,data=payload)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textprint("Password changed: "+str(response=="true"))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/pwdreset/api");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"password\": \"new_password\""+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;while((output=br.readLine())!=null){response+=output;}System.out.println("Password changed: "+("true".equals(response)));conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "password": "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: user_key',// Use this when using session key authentication
'Session_key: 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"));}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/pwdreset/api")payload={"password":"new_password"}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Password changed "+responseelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"password\": \"new_password\""+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/pwdreset/api","POST",payload);Console.WriteLine("Password changed: "+response);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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"=>"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
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/status");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){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: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/status")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/status");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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:
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact")payload={"email":"EMAIL","phoneNumber":"PHONENUMBER","name":"NAME","surname":"SURNAME","gender":"GENDER","fax":"FAX","zip":"ZIP","address":"ADDRESS","city":"CITY","province":"PROVINCE","birthdate":"BIRTHDATE","groupIds":["GRP1","GRP2"]}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="201"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"email\": \"EMAIL\", "+" \"phoneNumber\": \"PHONENUMBER\", "+" \"name\": \"NAME\", "+" \"surname\": \"SURNAME\", "+" \"gender\": \"GENDER\", "+" \"fax\": \"FAX\", "+" \"zip\": \"ZIP\", "+" \"address\": \"ADDRESS\", "+" \"city\": \"CITY\", "+" \"province\": \"PROVINCE\", "+" \"birthdate\": \"BIRTHDATE\", "+" \"groupIds\": ["+" \"GRP1\", "+" \"GRP2\""+" ]"+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/contact","POST",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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"=>"EMAIL","phoneNumber"=>"PHONENUMBER","name"=>"NAME","surname"=>"SURNAME","gender"=>"GENDER","fax"=>"FAX","zip"=>"ZIP","address"=>"ADDRESS","city"=>"CITY","province"=>"PROVINCE","birthdate"=>"BIRTHDATE","groupIds"=>["GRP1","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
email
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)
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/contacts")payload={"contacts":[{"email":"EMAIL","phoneNumber":"PHONENUMBER","name":"NAME","surname":"SURNAME"},{"email":"EMAIL","phoneNumber":"PHONENUMBER","name":"NAME","surname":"SURNAME"}],"updateExistingContact":true}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"contacts\": ["+" {"+" \"email\": \"EMAIL\", "+" \"phoneNumber\": \"PHONENUMBER\", "+" \"name\": \"NAME\", "+" \"surname\": \"SURNAME\""+" }, "+" {"+" \"email\": \"EMAIL\", "+" \"phoneNumber\": \"PHONENUMBER\", "+" \"name\": \"NAME\", "+" \"surname\": \"SURNAME\""+" }"+" ], "+" \"updateExistingContact\": true"+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/contacts","POST",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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"=>"EMAIL","phoneNumber"=>"PHONENUMBER","name"=>"NAME","surname"=>"SURNAME"},{"email"=>"EMAIL","phoneNumber"=>"PHONENUMBER","name"=>"NAME","surname"=>"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:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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/contact_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/contact/contact_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/contact/contact_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact/contact_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/contact/contact_id");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/contact/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:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/contact");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){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: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/contact");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/contacts/fields");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){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: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/contacts/fields")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/contacts/fields");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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/contact_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/contact_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/contact_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/contact_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/contact_id","POST",null);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist/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/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
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="["+" \"AV3vrSlPuGYfQz6BgjeI\", "+" \"BVvrSlPuGYfQz6BgjeI\""+"]";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){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: user_key',// Use this when using session key authentication
'Session_key: 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!');}?>
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 objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="["+" \"AV3vrSlPuGYfQz6BgjeI\", "+" \"BVvrSlPuGYfQz6BgjeI\""+"]";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist_batch","POST",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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=phone_number",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=phone_number");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=phone_number');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=phone_number")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=phone_number","POST",null);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/contact/add_to_blacklist?phoneNumber=".uri_escape("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=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.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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": "NAME",
"description": "DESCRIPTION"
}"""r=requests.post("https://api.textanywhere.com/API/v1.0/REST/group",headers=headers,data=payload)ifr.status_code!=201:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/group");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"name\": \"NAME\", "+" \"description\": \"DESCRIPTION\""+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=201){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "name": "NAME", '.' "description": "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: user_key',// Use this when using session key authentication
'Session_key: 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!');}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/group")payload={"name":"NAME","description":"DESCRIPTION"}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="201"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"name\": \"NAME\", "+" \"description\": \"DESCRIPTION\""+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/group","POST",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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"=>"NAME","description"=>"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.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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": "NAME",
"description": "DESCRIPTION"
}"""r=requests.put("https://api.textanywhere.com/API/v1.0/REST/group/group_id",headers=headers,data=payload)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/group/group_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"name\": \"NAME\", "+" \"description\": \"DESCRIPTION\""+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "name": "NAME", '.' "description": "DESCRIPTION"'.'}';$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/group/group_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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!');}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/group/group_id")payload={"name":"NAME","description":"DESCRIPTION"}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Put.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"name\": \"NAME\", "+" \"description\": \"DESCRIPTION\""+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/group/group_id","PUT",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/group/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"=>"NAME","description"=>"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/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.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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/groupid",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/group/groupid");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/group/groupid');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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!');}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/group/groupid")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Delete.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/group/groupid","DELETE",newNameValueCollection());Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/group/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.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/groups");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){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: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/groups")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/groups");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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=page&pageSize=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
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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/group_id/contact/contact_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/group/group_id/contact/contact_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/group/group_id/contact/contact_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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!');}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/group/group_id/contact/contact_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/group/group_id/contact/contact_id","POST",null);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/group/group_id/contact/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/group_id/contact/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
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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/group_id/contact/contact_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/group/group_id/contact/contact_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/group/group_id/contact/contact_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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!');}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/group/group_id/contact/contact_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Delete.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/group/group_id/contact/contact_id","DELETE",newNameValueCollection());Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/group/group_id/contact/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.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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": "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)ifr.status_code!=201:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/sms");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"message_type\": \"MESSAGE_TYPE\", "+" \"message\": \"Hello world!\", "+" \"recipient\": ["+" \"+443471234567\", "+" \"+443471234568\""+" ], "+" \"sender\": \"MySender\", "+" \"scheduled_delivery_time\": \"20161223101010\", "+" \"order_id\": \"123456789\", "+" \"returnCredits\": true"+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=201){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "message_type": "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: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/sms")payload={"message_type":"MESSAGE_TYPE","message":"Hello world!","recipient":["+443471234567","+443471234568"],"sender":"MySender","scheduled_delivery_time":"20161223101010","order_id":"123456789","returnCredits":true}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="201"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"message_type\": \"MESSAGE_TYPE\", "+" \"message\": \"Hello world!\", "+" \"recipient\": ["+" \"+443471234567\", "+" \"+443471234568\""+" ], "+" \"sender\": \"MySender\", "+" \"scheduled_delivery_time\": \"20161223101010\", "+" \"order_id\": \"123456789\", "+" \"returnCredits\": true"+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/sms","POST",payload);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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"=>"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
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
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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": "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)ifr.status_code!=201:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/paramsms");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"message_type\": \"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\""+" }"+" }"+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=201){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "message_type": "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: user_key',// Use this when using session key authentication
'Session_key: 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] requestvarrequest=require('request');request({url:'https://api.textanywhere.com/API/v1.0/REST/paramsms',method:'POST',headers:{'user_key':'user_key','Session_key':'session_key'},json:true,body:{"message_type":"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":"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 objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="201"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"message_type\": \"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\""+" }"+" }"+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/paramsms","POST",payload);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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"=>"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
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
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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": "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)ifr.status_code!=201:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/smstogroups");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"message_type\": \"MESSAGE_TYPE\", "+" \"message\": \"Hello world!\", "+" \"recipientsGroupdIds\": ["+" \"idGroup1\", "+" \"idGroup2\""+" ], "+" \"sender\": \"MySender\", "+" \"scheduled_delivery_time\": \"20161223101010\", "+" \"order_id\": \"123456789\", "+" \"returnCredits\": true"+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=201){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "message_type": "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: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/smstogroups")payload={"message_type":"MESSAGE_TYPE","message":"Hello world!","recipientsGroupdIds":["idGroup1","idGroup2"],"sender":"MySender","scheduled_delivery_time":"20161223101010","order_id":"123456789","returnCredits":true}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="201"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"message_type\": \"MESSAGE_TYPE\", "+" \"message\": \"Hello world!\", "+" \"recipientsGroupdIds\": ["+" \"idGroup1\", "+" \"idGroup2\""+" ], "+" \"sender\": \"MySender\", "+" \"scheduled_delivery_time\": \"20161223101010\", "+" \"order_id\": \"123456789\", "+" \"returnCredits\": true"+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/smstogroups","POST",payload);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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"=>"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
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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/order_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/sms/order_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/sms/order_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/sms/order_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/sms/order_id");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/sms/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/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]
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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/order_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/sms/order_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/sms/order_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/sms/order_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Delete.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/sms/order_id","DELETE",newNameValueCollection());dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/sms/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/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”)
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/sms/bulk");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){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: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/sms/bulk")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Delete.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/sms/bulk","DELETE",newNameValueCollection());dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::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):
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.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'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=date",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/smshistory?from=date");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/smshistory?from=date');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/smshistory?from=date")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/smshistory?from=date");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/smshistory?from=".uri_escape("date")."";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
{"total":1,"// The total number of results""pageNumber":1,"// The returned page number""result":"OK","// The status of the request""pageSize":10,"// The page size""smshistory":["// The SMS history"{"order_id":"XYZABCQWERTY","// The order ID""create_time":"yyyyMMddHHmmss","// When the order was created""schedule_time":"yyyyMMddHHmmss","// When the sending is scheduled""message_type":"GP","// The message type","message":"Text message","sender":"MySender","// The sender's alias""num_recipients":2"// The number of recipients"},{...}]}
Returns the user’s SMS messages history
HTTP request
GET /API/v1.0/REST/smshistory?from=fromdate&to=todate&pageNumber=page&pageSize=size
Parameters
Parameter
Type
Description
Required
Default
from
Date(yyyyMMddHHmmss)
Return results from the given date
Yes
-
to
Date(yyyyMMddHHmmss)
Return results up to the given date
No
now
timezone
Timezone(IANA time zone)
Optional timezone applied to from or to dates
No
-
pageNumber
Int
Return the given results page
No
1
pageSize
Int
The number of results in a page
No
10
Returns
Code
Description
200
A paginated list of the SMS history filtered as specified by the from and to dates.
400
from parameter not specified, or an error in the from, to or timezone date format. Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=recipient&from=date",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=recipient&from=date");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=recipient&from=date');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=recipient&from=date")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=recipient&from=date");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/rcptHistory?recipient=".uri_escape("recipient")."&from=".uri_escape("date")."";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
{"total":1,"// The total number of results""pageNumber":1,"// The returned page number""result":"OK","// The status of the request""pageSize":10,"// The page size""rcpthistory":["// The SMS history"{"order_id":"XYZABCQWERTY","// The order ID""create_time":"yyyyMMddHHmmss","// When the order was created""schedule_time":"yyyyMMddHHmmss","// When the sending is scheduled""message_type":"GP","// The message type""sender":"MySender","// The sender's alias""campaign_name":"MyCampaign","// The campaign name""send_time":"yyyyMMddHHmmss","// When the message is sent""delivery_time":"yyyyMMddHHmmss","// When the message is arrive to the phone""status":4,"// Status of message""destination":"+XXXXXXXXXX","// Recipient number""first_click_date":"yyyyMMddHHmmss","// (Optional, present for Rich SMS) When the embedded link was clicked first""last_click_date":"yyyyMMddHHmmss","// (Optional, present for Rich SMS) When the embedded link was clicked last""total_clicks":"561""// (Optional, present for Rich SMS) Total number of clicks on the link"},{...}]}
Returns the user’s SMS messages history for the specified recipient
HTTP request
GET /API/v1.0/REST/rcptHistory?recipient=recipient&from=fromdate&to=todate&pageNumber=page&pageSize=size
Parameters
Parameter
Type
Description
Required
Default
recipient
Recipient in ‘+cnnnnnnn’ format where c is country prefix and n the digits of the number
Return status only of sms sent to this number
Yes
-
from
Date(yyyyMMddHHmmss)
Return results from the given date
Yes
-
to
Date(yyyyMMddHHmmss)
Return results up to the given date
No
now
timezone
Timezone(IANA time zone)
Optional timezone applied to from or to dates
No
-
pageNumber
Int
Return the given results page
No
1
pageSize
Int
The number of results in a page
No
10
Returns
Code
Description
200
A paginated list of the SMS history filtered as specified by recipient and the from/to dates.
400
recipient or from parameter not specified, or an error in the from, to or timezone date format. Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=order_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=order_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=order_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=order_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=order_id");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/smsrich/statistics?order_id=".uri_escape("order_id")."";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
{"summary":{"// Summary data of the clicks on the links for this sms campaign""uniqueClicks":124,"// How many recipients clicked on the sms link""totalClicks":172,"// Total number of clicks (a single recipient can click multiple times)""sentShortUrls":200,"// Total messages sent with a correct link inside""percentageClickedOnSent":62"// uniqueClicks / sentShortUrls"},"aggregate":{"// Data aggregated by how the links were opened""total":4,"// Total messages sent with a correct link inside""os":{"// Operating System used when opening the link (Microsoft, Linux, Android)""Linux":{"clicks":14,"percentage":12},"Android":{"clicks":110,"percentage":88}},"browser":{"// Browser used when opening the link (Chrome, Firefox, Safari)""Unknown":{"clicks":15,"percentage":12},"Chrome 8":{"clicks":66,"percentage":53},"Firefox":{"clicks":43,"percentage":35}},"device":{"// Device used when opening the link (Computer, Mobile)""Mobile":{"clicks":110,"percentage":88},"Computer":{"clicks":14,"percentage":12}}}}
After sending an sms campaign via API containing a Rich sms shortened link, this api returns that sms link’s opening statistics.
Keep in mind that you need to use a unique order_id when sending and store it to request in the near future.
HTTP request
GET /API/v1.0/REST/smsrich/statistics?order_id=order_id
Parameters
Parameter
Type
Description
Required
Default
order_id
String
The order_id specified when sending the message
Yes
-
Returns
Code
Description
200
Summury and aggregated data for the link opening if the message specified exists.
400
order_id parameter not specified, or no message identified by it
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
404
[Not found] The User_key was not found
SMS Blacklist / Stop SMS
This is the part of the API that allow to insert and to retrieve the list of SMS blacklist / Stop SMS.
The SMS blacklist contains the phone numbers to which you don’t want to send any SMS.
If the Stop SMS Service is active, any person who receive an SMS can add their phone number to the blacklist.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.post("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=phoneNumber",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=phoneNumber");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=phoneNumber');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=phoneNumber")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=phoneNumber","POST",null);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?phoneNumber=".uri_escape("phoneNumber")."";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
true
Add phone number to SMS blacklist.
The phone number will no longer receive an SMS from the user requesting the addition to the blacklist.
HTTP request
POST /API/v1.0/REST/blacklist/sms
Query params
Parameter
Type
Description
Required
Default
phoneNumber
String
The phone number of the user. The format must be +441234567890 or 00441234567890
Yes
-
Returns
Code
Description
200
The phone number is successfully added.
400
[Bad request] Invalid recipient.
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }payload="""[
"+4434015546",
"+4434025546"
]"""r=requests.post("https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch",headers=headers,data=payload)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="["+" \"+4434015546\", "+" \"+4434025546\""+"]";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='['.' "+4434015546", '.' "+4434025546"'.']';$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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!');}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch")payload=["+4434015546","+4434025546"]# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="["+" \"+4434015546\", "+" \"+4434025546\""+"]";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch","POST",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/blacklist/smsbatch";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload=["+4434015546","+4434025546"];$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;print"Success!";}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
2
Add multiple numbers to the user’s blacklist.
HTTP request
POST /API/v1.0/REST/blacklist/smsbatch
Body fields
Parameter
Type
Description
Required
Default
—
List(String)
Array of phone numbers
Yes
“”
Returns
Code
Description
200
Number of phone numbers correctly put in the blacklist
400
Some of the phone numbers specified were badly formatted
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=from&to=to&origins=origins&pageNumber=pageNumber&pageSize=pageSize&number=number",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=from&to=to&origins=origins&pageNumber=pageNumber&pageSize=pageSize&number=number");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=from&to=to&origins=origins&pageNumber=pageNumber&pageSize=pageSize&number=number');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=from&to=to&origins=origins&pageNumber=pageNumber&pageSize=pageSize&number=number")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=from&to=to&origins=origins&pageNumber=pageNumber&pageSize=pageSize&number=number");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/blacklist/sms?from=".uri_escape("from")."&to=".uri_escape("to")."&origins=".uri_escape("origins")."&pageNumber=".uri_escape("pageNumber")."&pageSize=".uri_escape("pageSize")."&number=".uri_escape("number")."";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
{"totalElements":3,"// The total number of results""totalPages":1,"// The total pages of results""last":true,"// Is last page""first":true,"// Is first page""size":10,"// Page size""number":0,"// Page number""sort":null,"// Sort""numberOfElements":3,"// Number of element in page""content":[{"number":"+44123456789","// The complete phone number""idNation":"ita","// The nation of phone number""rcptPrefix":"123","// The operator prefix""rcptNumber":"456789","// The number""origin":"API","// Origin of insert (API, WEB, STOPSMS)""insertTime":"2018-10-10 08:00:00""// The datetime of insert in blacklist"},{...}]}
Retrieve the paginated list of Phone numbers in SMS Blacklist
HTTP request
GET /API/v1.0/REST/blacklist/sms
Query params
Parameter
Type
Description
Required
Default
from
Date(yyyy-MM-dd HH:mm:ss)
Return results from the given date
No
-
to
Date(yyyy-MM-dd HH:mm:ss)
Return results up to the given date
No
-
timezone
Timezone(IANA time zone)
Optional timezone applied to from or to dates
No
-
number
String
Return results that contain this phone number or part of it.
No
-
origins
String
List of origins(API, WEB, STOPSMS) separated by ‘,’ used for filter the results
No
-
pageNumber
String
Return the given results page
No
-
pageSize
String
The number of results in a page
No
-
Returns
Code
Description
200
A paginated list of phone number in blacklist.
400
Some of the parameters specified were badly formatted
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
404
[Not found] The User_key was not found
Received SMS API
This API allows to query the received SMS messages on the owned SIMs.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/newsrsmsmessage";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
Returns the list of received messages on the given sim_id since the
last call of this method, or the beginning of time if it’s the first
call. The list is limited to max. 100 entries.
HTTP request
For all SIMs, use:
GET /API/v1.0/REST/newsrsmsmessage?limit=limit
For one or more specific SIMs, use:
GET /API/v1.0/REST/newsrsmsmessage/id_sim?limit=limit
Parameters
Parameter
Type
Description
Required
Default
id_sim
String(PhoneNumber)
The phone number where you enabled the service of reception, in international format (+443471234567 or 00443471234567). If no SIM is specified, returns the new messages for all enabled SIMs. It is possible to specify more numbers, separated by comma
No
All SIMs
limit
Int (max 100)
The max. number of entries returned
No
100
Returns
Code
Description
200
The list of received SMS messages since the last call of this method.
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=from_date",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=from_date");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=from_date');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=from_date")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=from_date");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/srsmshistory?from=".uri_escape("from_date")."";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
GET /API/v1.0/REST/srsmshistory?from=fromdate&to=todate&pageNumber=page&pageSize=size
For one or more specific SIMs, use:
GET /API/v1.0/REST/srsmshistory/{id_sim}?from={fromdate}&to={todate}&pageNumber={page}&pageSize={size}
Parameters
Parameter
Type
Description
Required
Default
id_sim
String(PhoneNumber)
The phone number where you enabled the service of reception, in international format (+443471234567 or 00443471234567). If no SIM is specified, returns the new messages for all enabled SIMs. It is possible to specify more numbers, separated by comma
No
All SIMs
from
Date(yyyyMMddHHmmss)
Return results from the given date
Yes
-
to
Date(yyyyMMddHHmmss)
Return results up to the given date
No
now
timezone
Timezone(IANA time zone)
Optional timezone applied to from or to dates
No
-
pageNumber
Int
Return the given results page
No
1
pageSize
Int
The number of results in a page
No
10
Returns
Code
Description
200
The paginated list of received SMS messages.
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
404
[Not found] The User_key was not found
Get the received SMS messages after a specified message.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/srsmshistory/id_sim/id_message",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/srsmshistory/id_sim/id_message");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/srsmshistory/id_sim/id_message');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/srsmshistory/id_sim/id_message")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/srsmshistory/id_sim/id_message");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/srsmshistory/id_sim/id_message";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/mosmshistory",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/mosmshistory");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/mosmshistory');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/mosmshistory")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/mosmshistory");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/mosmshistory";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
This feature is available only for French customers!
Returns a list (limited to max. 100 entries) of MO messages received for the given type which must be STOP or CONTACT or OTHER;
type is a mandatory parameter, the others are optional.
HTTP request
GET /API/v1.0/REST/mosmshistory?type=type&from=fromdate&to=todate&pageNumber=page&pageSize=size
Parameters
Parameter
Type
Description
Required
Default
type
String (“STOP” or “CONTACT” or “OTHER”)
Type of the MO, which must be one of STOP, CONTACT or OTHER
Yes
-
from
Date(yyyyMMddHHmmss)
Return results from the given date
No
-
to
Date(yyyyMMddHHmmss)
Return results up to the given date
No
-
timezone
Timezone(IANA time zone)
Optional timezone applied to from or to dates
No
-
pageNumber
Int
Return the given results page
No
1
pageSize
Int
The number of results in a page
No
10
Returns
Code
Description
200
The list of received MO messages of type, with the specified time constraints (if any) and paging
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided, or the user is not French
404
[Not found] The User_key was not found
SMS template API
This is the part of the API that allows to create message templates.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }payload="""{
"name": "my template-1",
"text": "Hello World!",
"encoding": "GSM",
"sender": "my sender"
}"""r=requests.post("https://api.textanywhere.com/API/v1.0/REST/template",headers=headers,data=payload)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/template");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"name\": \"my template-1\", "+" \"text\": \"Hello World!\", "+" \"encoding\": \"GSM\", "+" \"sender\": \"my sender\""+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "name": "my template-1", '.' "text": "Hello World!", '.' "encoding": "GSM", '.' "sender": "my sender"'.'}';$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/template');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: session_key',// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);$response=curl_exec($ch);$info=curl_getinfo($ch);curl_close($ch);if($info['http_code']!=200){echo('Error! http code: '.$info['http_code'].', body message: '.$response);}else{$obj=json_decode($response);print_r($obj);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/template")payload={"name":"my template-1","text":"Hello World!","encoding":"GSM","sender":"my sender"}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"name\": \"my template-1\", "+" \"text\": \"Hello World!\", "+" \"encoding\": \"GSM\", "+" \"sender\": \"my sender\""+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/template","POST",payload);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/template";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload={"name"=>"my template-1","text"=>"Hello World!","encoding"=>"GSM","sender"=>"my sender"};$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the result of the operation and the id of the new template:
It is possible to include a link to a published Landing Page by
specifying the id_landing parameter and by adding the following
placeholder in the message body: %PAGESLINK____________%.
Landing pages must be first created and published in your user
panel, since you will need id_landing to send it.
A list of published landing pages can be retrieved by using
the Landing Pages APIs
SMS Link Analytics
When including URLs in the message, it may be convenient to use our SMS Link Analytics short URLs service to limit the number of characters used in the SMS message and having statistic on clic.
Our API can automatically generate a short link starting from a long one, and add it in the message.
To use this feature, use the %RICHURL________% placeholder in the message body, that will be replaced with the generated short link, and the respective richsms_url parameter, that should be set to a valid URL.
Sender Alias
Alphanumeric aliases are required to be registered first, and need to be
approved both from Us and AGCOM.
Aliases can be used only with high-quality message types.
HTTP request
POST /API/v1.0/REST/template
Body fields
The body must contain a Json with all the template info:
Parameter
Type
Description
Required
Default
name
String
Name of template
Yes
text
String (max 1000 chars with “gsm” encoding, 450 with “ucs2” encoding)
The body of the message. *Message max length could be 160 chars when using low-quality SMSs. New line char needs to be codified as “\n”.
Yes
-
encoding
String (“GSM” or “UCS2”)
The SMS encoding. Use UCS2 for non standard character sets.
Yes
-
sender
String
The Sender name. If the message type allows a custom TPOA and the field is left empty, the user’s preferred TPOA is used. Must be empty if the message type does not allow a custom TPOA.
No
-
richUrl
String
The url where the rich url redirects. Also add the %RICHURL________% placeholder in the message body.
No
-
idPage
Int
The id of the published page. Also add the %PAGESLINK____________% placeholder in the message body.
No
-
Returns
Code
Description
200
Successful request
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/template",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/template");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/template');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/template")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/template");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/template";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/template/template",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/template/template");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/template/template');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/template/template")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/template/template");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/template/template";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }payload="""[
{
"op": "replace",
"path": "/text",
"value": "new message"
}
]"""r=requests.patch("https://api.textanywhere.com/API/v1.0/REST/template/group_id",headers=headers,data=payload)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/template/group_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","session_key");// When using Access Token authentication, use this instead:// conn.setRequestProperty("Access_token", "UserParam{access_token}");conn.setRequestMethod("PATCH");conn.setRequestProperty("Accept","application/json");conn.setRequestProperty("Content-type","application/json");conn.setDoOutput(true);Stringpayload="["+" {"+" \"op\": \"replace\", "+" \"path\": \"/text\", "+" \"value\": \"new message\""+" }"+"]";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='['.' {'.' "op": "replace", '.' "path": "/text", '.' "value": "new message"'.' }'.']';$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/template/group_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: session_key',// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);$response=curl_exec($ch);$info=curl_getinfo($ch);curl_close($ch);if($info['http_code']!=200){echo('Error! http code: '.$info['http_code'].', body message: '.$response);}else{echo('Success!');}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/template/group_id")payload=[{"op":"replace","path":"/text","value":"new message"}]# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Patch.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="["+" {"+" \"op\": \"replace\", "+" \"path\": \"/text\", "+" \"value\": \"new message\""+" }"+"]";wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/template/group_id","DELETE",newNameValueCollection());Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/template/group_id";my$req=HTTP::Request->new(PATCH=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload=[{"op"=>"replace","path"=>"/text","value"=>"new message"}];$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;print"Success!";}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.delete("https://api.textanywhere.com/API/v1.0/REST/template/template_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/template/template_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/template/template_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/template/template_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Delete.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/template/template_id","DELETE",newNameValueCollection());dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/template/template_id";my$req=HTTP::Request->new(DELETE=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
{"result":"OK"}
Deletes the given user’s message template.
HTTP request
DELETE /API/v1.0/REST/template/template_id
Parameters
Parameter
Type
Description
Required
Default
template_id
Int
The template ID
Yes
-
Returns
Code
Description
200
Template successfully deleted
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
404
[Not found] The template was not found
Subaccount API
If enabled as a superaccount, the user can create subaccounts that
can be assigned to third-parties. Superaccounts may or may not share
credits with their subaccounts.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccounts",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccounts");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccounts');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccounts")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccounts");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccounts";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount")payload={"address":"via xxx","cell":"+443393939393","city":"myCity","fiscal-code":"BRGRJM87J89JH907E","company":true,"company-name":"myCompany","credit-eat-mode":1,"dfeu":true,"email":"em@a.il","fax":"0461686868","invoicing-email":"em@a.il","language":"ita","login":"myLogin","name":"myNome","num-cell-for-test-sms":"+443393939393","password":"myPassword","phone":"0461656565","piva":"104456015145","province":"TN","superaccount":false,"surname":"mySurname","use24":true,"zip-code":"38010","id-subaccount-profile":1}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"address\": \"via xxx\", "+" \"cell\": \"+443393939393\", "+" \"city\": \"myCity\", "+" \"fiscal-code\": \"BRGRJM87J89JH907E\", "+" \"company\": true, "+" \"company-name\": \"myCompany\", "+" \"credit-eat-mode\": 1, "+" \"dfeu\": true, "+" \"email\": \"em@a.il\", "+" \"fax\": \"0461686868\", "+" \"invoicing-email\": \"em@a.il\", "+" \"language\": \"ita\", "+" \"login\": \"myLogin\", "+" \"name\": \"myNome\", "+" \"num-cell-for-test-sms\": \"+443393939393\", "+" \"password\": \"myPassword\", "+" \"phone\": \"0461656565\", "+" \"piva\": \"104456015145\", "+" \"province\": \"TN\", "+" \"superaccount\": false, "+" \"surname\": \"mySurname\", "+" \"use24\": true, "+" \"zip-code\": \"38010\", "+" \"id-subaccount-profile\": 1"+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount","POST",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload={"address"=>"via xxx","cell"=>"+443393939393","city"=>"myCity","fiscal-code"=>"BRGRJM87J89JH907E","company"=>true,"company-name"=>"myCompany","credit-eat-mode"=>1,"dfeu"=>true,"email"=>"em@a.il","fax"=>"0461686868","invoicing-email"=>"em@a.il","language"=>"ita","login"=>"myLogin","name"=>"myNome","num-cell-for-test-sms"=>"+443393939393","password"=>"myPassword","phone"=>"0461656565","piva"=>"104456015145","province"=>"TN","superaccount"=>false,"surname"=>"mySurname","use24"=>true,"zip-code"=>"38010","id-subaccount-profile"=>1};$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;print"Success!";}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
{"result":"Ok","idSubaccount":"10"}
# HTTP header includes location response that points to the created subaccount:
'Location': '/subaccount/10'
Creates a new subaccount for the authenticated user, which has to be a
superaccount.
HTTP request
POST /API/v1.0/REST/subaccount
Body fields
Parameter
Type
Description
Required
Default
address
String
The subaccount address
No
-
cell
String
The subaccount mobile phone number
Yes
-
city
String
The subaccount city
No
-
company
Bool
DEPRECATED sub can be only a company - Is the subaccount a company?
No
true
company-name
String
The company name
Yes (if company=true)
-
credit-eat-mode
Int (0, 1, 2)
DEPRECATED automatically derived by the super account settings - Tells from who credits are scaled. 0 = own credits, 1 = superaccount credits, 2 = own credits and superaccount ones
No
-
dfeu
Bool
Use the Date Format in EUropean format
No
true
email
String (a valid Email)
The subaccount’s operational email. It is used to receive reports, alerts and communications.
Yes
-
fax
String
The subaccount FAX number
No
“”
invoicing-email
String (a valid Email)
If provided, invoices will be sent here instead of the default email
No
“”
language
String
The subaccount language. If none, defaults to the one of the superaccount
No
to the one of the superaccount
login
String
The subaccount login must be a valid and unique email
Yes
-
name
String
The subaccount owner first name
Yes
-
num-cell-for-test-sms
String (Phone number)
A phone number where test SMS messages will be sent
No
“”
password
String
The subaccount Web password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.)
No
If null, will be autogenerated
passwordApi
String
The subaccount Api password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.)
No
If null, will be the same of Web password
phone
String (PhoneNumber)
The subaccount phone number
No
“”
piva
String
The subaccount VAT number (P.Iva in Italy)
No
province
String
The subaccount province
No
-
superaccount
Bool
The subaccount is a superaccount itself (i.e. it can create his own subaccounts)
No
false
surname
String
The subaccount last name
Yes
-
use24
Bool
Use the 24 hour format for time
No
true
zip-code
String
The subaccount ZIP Code
No
-
id-subaccount-profile
Int
Specifying a custom subaccount profile allows a superaccount to narrow down the subaccount enabled features (e.g. Only send SMS messages, or even further, only send a specific type of SMS message)
No
The default profile
Returns
Code
Description
200
Success, returns a response body specifyng the id of new subaccount and HTTP location header pointing to the created subaccount
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id")payload={"address":"via xxx","cell":"+443393939393","city":"myCity","fiscal-code":"BRGRJM87J89JH907E","company":true,"company-name":"myCompany","credit-eat-mode":1,"dfeu":true,"email":"em@a.il","fax":"0461686868","invoicing-email":"em@a.il","language":"ita","name":"myNome","num-cell-for-test-sms":"+443393939393","password":"myPassword","phone":"0461656565","piva":"104456015145","province":"TN","superaccount":false,"surname":"mySurname","use24":true,"zip-code":"38010","id-subaccount-profile":1}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Put.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"address\": \"via xxx\", "+" \"cell\": \"+443393939393\", "+" \"city\": \"myCity\", "+" \"fiscal-code\": \"BRGRJM87J89JH907E\", "+" \"company\": true, "+" \"company-name\": \"myCompany\", "+" \"credit-eat-mode\": 1, "+" \"dfeu\": true, "+" \"email\": \"em@a.il\", "+" \"fax\": \"0461686868\", "+" \"invoicing-email\": \"em@a.il\", "+" \"language\": \"ita\", "+" \"name\": \"myNome\", "+" \"num-cell-for-test-sms\": \"+443393939393\", "+" \"password\": \"myPassword\", "+" \"phone\": \"0461656565\", "+" \"piva\": \"104456015145\", "+" \"province\": \"TN\", "+" \"superaccount\": false, "+" \"surname\": \"mySurname\", "+" \"use24\": true, "+" \"zip-code\": \"38010\", "+" \"id-subaccount-profile\": 1"+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id","PUT",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id";my$req=HTTP::Request->new(PUT=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload={"address"=>"via xxx","cell"=>"+443393939393","city"=>"myCity","fiscal-code"=>"BRGRJM87J89JH907E","company"=>true,"company-name"=>"myCompany","credit-eat-mode"=>1,"dfeu"=>true,"email"=>"em@a.il","fax"=>"0461686868","invoicing-email"=>"em@a.il","language"=>"ita","name"=>"myNome","num-cell-for-test-sms"=>"+443393939393","password"=>"myPassword","phone"=>"0461656565","piva"=>"104456015145","province"=>"TN","superaccount"=>false,"surname"=>"mySurname","use24"=>true,"zip-code"=>"38010","id-subaccount-profile"=>1};$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;print"Success!";}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# # HTTP header includes location response that points to the updated subaccount:
'Location': '/subaccount/18107'
Edits the subaccount identified by the given subaccount_id. Calling
user must be a superaccount.
HTTP request
PUT /API/v1.0/REST/subaccount/subaccount_id?lock-subaccount=value
Parameters
Parameter
Type
Description
Required
Default
subaccount_id
Int
The subaccount ID
Yes
-
lock-subaccount
Bool
Activate or deactivate the subaccount
No
false
Body fields
Parameter
Type
Description
Required
Default
address
String
The subaccount address
No
-
cell
String
The subaccount mobile phone number
Yes
-
city
String
The subaccount city
No
-
company
Bool
DEPRECATED sub can be only a company - Is the subaccount a company?
No
true
company-name
String
The company name
Yes (if company=true)
-
credit-eat-mode
Int (0, 1, 2)
DEPRECATED automatically derived by the super account settings - Tells from who credits are scaled. 0 = own credits, 1 = superaccount credits, 2 = own credits and superaccount ones
No
-
dfeu
Bool
Use the Date Format in EUropean format
No
true
email
String (a valid Email)
The subaccount’s operational email. It is used to receive reports, alerts and communications.
Yes
-
registration-email
String (a valid Email)
The subaccount’s registration email. It is used to identify the account, must be unique.
No
-
fax
String
The subaccount FAX number
No
“”
invoicing-email
String (a valid Email)
If provided, invoices will be sent here instead of the default email
No
“”
language
String
The subaccount language. If none, defaults to the one of the superaccount
No
to the one of the superaccount
name
String
The subaccount owner first name
Yes
-
num-cell-for-test-sms
String (Phone number)
A phone number where test SMS messages will be sent
No
“”
password
String
The subaccount password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.)
No
If null, will keep current password
passwordApi
String
The subaccount Api password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.)
No
If null, will keep current password
phone
String (PhoneNumber)
The subaccount phone number
No
“”
piva
String
The subaccount VAT number (P.Iva in Italy)
No
province
String
The subaccount province
No
-
superaccount
Bool
The subaccount is a superaccount itself (i.e. it can create his own subaccounts)
No
false
surname
String
The subaccount last name
Yes
-
use24
Bool
Use the 24 hour format for time
No
true
zip-code
String
The subaccount ZIP Code
No
-
id-subaccount-profile
Int
Specifying a custom subaccount profile allows a superaccount to narrow down the subaccount enabled features (e.g. Only send SMS messages, or even further, only send a specific type of SMS message)
No
The default profile
Returns
Code
Description
200
Success, returns an empty response with the HTTP location header pointing to the updated subaccount
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }payload="""{
"passwd": "password"
}"""r=requests.post("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd",headers=headers,data=payload)ifr.status_code!=201:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"passwd\": \"password\""+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=201){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "passwd": "password"'.'}';$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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!');}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd")payload={"passwd":"password"}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="201"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"passwd\": \"password\""+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd","POST",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload={"passwd"=>"password"};$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==201){my$response=$resp->decoded_content;print"Success!";}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# The HTTP location header that points to the subaccount 'change password' URL:
'Location': '/subaccount/{subaccount_id}/changepwd'
Change a subaccount’s password
HTTP request
POST /API/v1.0/REST/subaccount/subaccount_id/changepwd
Parameters
Parameter
Type
Description
Required
Default
subaccount_id
Int
The subaccount ID
Yes
-
Body fields
Parameter
Type
Description
Required
Default
passwd
String
The subaccount password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.)
Yes
-
Returns
Code
Description
201
Password correctly changed. HTTP location header pointing to the change password URL.
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }payload="""{
"passwd": "password"
}"""r=requests.post("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd/api",headers=headers,data=payload)ifr.status_code!=201:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd/api");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"passwd\": \"password\""+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=201){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "passwd": "password"'.'}';$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd/api');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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!');}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd/api")payload={"passwd":"password"}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="201"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"passwd\": \"password\""+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd/api","POST",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/changepwd/api";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload={"passwd"=>"password"};$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==201){my$response=$resp->decoded_content;print"Success!";}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# The HTTP location header that points to the subaccount 'change password' URL:
'Location': '/subaccount/{subaccount_id}/changepwd/api'
Change a subaccount’s password
HTTP request
POST /API/v1.0/REST/subaccount/subaccount_id/changepwd/api
Parameters
Parameter
Type
Description
Required
Default
subaccount_id
Int
The subaccount ID
Yes
-
Body fields
Parameter
Type
Description
Required
Default
passwd
String
The subaccount password (must be between 8 and 16 chars, 1 lower-case letter, 1 upper-case letter, 1 digit and 1 special character between !@#$%^&*.)
Yes
-
Returns
Code
Description
201
Password correctly changed. HTTP location header pointing to the change password URL.
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/credit",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/credit");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/credit');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/credit")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/credit");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/credit";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase")payload={"purchases":[{"super-to-sub":true,"price":25.0,"message-types":[{"message-type":"MESSAGE_TYPE_1","unit-price":1.1,"nation":"NATION_1"},{"message-type":"MESSAGE_TYPE_2","unit-price":0.7,"nation":"NATION_2"},{"message-type":"MESSAGE_TYPE_2","unit-price":1.5,"nation":"NATION_3"}]},{"super-to-sub":true,"price":37.0,"message-types":[{"message-type":"MESSAGE_TYPE_1","unit-price":1.2},{"message-type":"MESSAGE_TYPE_2","unit-price":0.8}]}]}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"purchases\": ["+" {"+" \"super-to-sub\": true, "+" \"price\": 25.0, "+" \"message-types\": ["+" {"+" \"message-type\": \"MESSAGE_TYPE_1\", "+" \"unit-price\": 1.1, "+" \"nation\": \"NATION_1\""+" }, "+" {"+" \"message-type\": \"MESSAGE_TYPE_2\", "+" \"unit-price\": 0.7, "+" \"nation\": \"NATION_2\""+" }, "+" {"+" \"message-type\": \"MESSAGE_TYPE_2\", "+" \"unit-price\": 1.5, "+" \"nation\": \"NATION_3\""+" }"+" ]"+" }, "+" {"+" \"super-to-sub\": true, "+" \"price\": 37.0, "+" \"message-types\": ["+" {"+" \"message-type\": \"MESSAGE_TYPE_1\", "+" \"unit-price\": 1.2"+" }, "+" {"+" \"message-type\": \"MESSAGE_TYPE_2\", "+" \"unit-price\": 0.8"+" }"+" ]"+" }"+" ]"+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase","POST",payload);Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload={"purchases"=>[{"super-to-sub"=>true,"price"=>25.0,"message-types"=>[{"message-type"=>"MESSAGE_TYPE_1","unit-price"=>1.1,"nation"=>"NATION_1"},{"message-type"=>"MESSAGE_TYPE_2","unit-price"=>0.7,"nation"=>"NATION_2"},{"message-type"=>"MESSAGE_TYPE_2","unit-price"=>1.5,"nation"=>"NATION_3"}]},{"super-to-sub"=>true,"price"=>37.0,"message-types"=>[{"message-type"=>"MESSAGE_TYPE_1","unit-price"=>1.2},{"message-type"=>"MESSAGE_TYPE_2","unit-price"=>0.8}]}]};$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;print"Success!";}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# The HTTP location header that points to the subaccount 'create purchase' URL:
'Location': '/subaccount/{subaccount_id}/purchase'
Creates one or more purchases for the given subaccount. Subaccount
credit-eat-mode must be 2. Caller must be a superaccount.
HTTP request
POST /API/v1.0/REST/subaccount/subaccount/purchase
Parameters
Parameter
Type
Description
Required
Default
subaccount_id
Int or String
The subaccount ID or Login
Yes
-
Body fields
Parameter
Type
Description
Required
Default
purchases
List(Purchase)
The list of purchases to be created
Yes
-
Purchase.message-types
List(MessageType)
The purchase’s message types
Yes
-
Purchase.price
Float
The quantity of purchased credits
Yes
-
MessageType.message-type
String
The message type (“GP” for Gold+)
Yes
-
MessageType.unit-price
Float
The cost for the subaccount of a unit of the respective message-type
Yes
-
MessageType.nation
String
The nation to which this price is bound, you must specify this paramenter only in case such nation is different from your account nation. Then nation must be specified in ISO-3166-1 format. If a nation is specified then the quality of the message must be high quality, otherwise the request will be rejected. This field is nullable since is not required
No
-
Note that you only want to specify the nation if it is different from your account nation.
For example, if you have got an Italian account and you want to give Italian credits, you don’t have to specify the nation.
Returns
Some errors may araise by the given call if you are specifying the nation.
An invalid nation code may be passed and the backend will give a
Value ‘NATION_1’ is not a valid iso 3166-1 value for parameter ‘nation’
or if the quality doesn’t match the highest quality possibile
Value ‘MESSAGE_TYPE_1’ is not a valid quality: when specifying a nation allowed quality is GP
Code
Description
200
Successful request. The HTTP location header that points to the subaccount ‘create purchase’ URL
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.delete("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase/purchase_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:print('Success!')
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase/purchase_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}System.out.println("Success!");conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase/purchase_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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!');}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase/purchase_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Delete.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyputs"Success!"elseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase/purchase_id","DELETE",newNameValueCollection());Console.WriteLine("Success!");}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/subaccount_id/purchase/purchase_id";my$req=HTTP::Request->new(DELETE=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;print"Success!";}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
{"result":"OK"}
Deletes a purchase of the given subaccount. Caller must be a
superaccount, and the Subaccount’s credit-eat-mode should be 2.
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }payload="""{
"name": "creation test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4ERSngBaas466fasfdqQK-sPYG32341PqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": false,
"enabledServices": [
"pages",
"sms",
"smsadv",
"richsms",
"email",
"rcp",
"sr"
],
"enabledSMSQualities": [
"GP",
"TI",
"SI",
"AD"
]
}"""r=requests.post("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile",headers=headers,data=payload)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"name\": \"creation test\", "+" \"isDefault\": false, "+" \"numSubaccount\": 0, "+" \"sharedGroups\": ["+" \"-4ERSngBaas466fasfdqQK-sPYG32341PqVx\""+" ], "+" \"sharedTemplates\": ["+" 30"+" ], "+" \"sharedBlacklists\": false, "+" \"enabledServices\": ["+" \"pages\", "+" \"sms\", "+" \"smsadv\", "+" \"richsms\", "+" \"email\", "+" \"rcp\", "+" \"sr\""+" ], "+" \"enabledSMSQualities\": ["+" \"GP\", "+" \"TI\", "+" \"SI\", "+" \"AD\""+" ]"+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "name": "creation test", '.' "isDefault": false, '.' "numSubaccount": 0, '.' "sharedGroups": ['.' "-4ERSngBaas466fasfdqQK-sPYG32341PqVx"'.' ], '.' "sharedTemplates": ['.' 30'.' ], '.' "sharedBlacklists": false, '.' "enabledServices": ['.' "pages", '.' "sms", '.' "smsadv", '.' "richsms", '.' "email", '.' "rcp", '.' "sr"'.' ], '.' "enabledSMSQualities": ['.' "GP", '.' "TI", '.' "SI", '.' "AD"'.' ]'.'}';$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: session_key',// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);$response=curl_exec($ch);$info=curl_getinfo($ch);curl_close($ch);if($info['http_code']!=200){echo('Error! http code: '.$info['http_code'].', body message: '.$response);}else{$obj=json_decode($response);print_r($obj);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile")payload={"name":"creation test","isDefault":false,"numSubaccount":0,"sharedGroups":["-4ERSngBaas466fasfdqQK-sPYG32341PqVx"],"sharedTemplates":[30],"sharedBlacklists":false,"enabledServices":["pages","sms","smsadv","richsms","email","rcp","sr"],"enabledSMSQualities":["GP","TI","SI","AD"]}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"name\": \"creation test\", "+" \"isDefault\": false, "+" \"numSubaccount\": 0, "+" \"sharedGroups\": ["+" \"-4ERSngBaas466fasfdqQK-sPYG32341PqVx\""+" ], "+" \"sharedTemplates\": ["+" 30"+" ], "+" \"sharedBlacklists\": false, "+" \"enabledServices\": ["+" \"pages\", "+" \"sms\", "+" \"smsadv\", "+" \"richsms\", "+" \"email\", "+" \"rcp\", "+" \"sr\""+" ], "+" \"enabledSMSQualities\": ["+" \"GP\", "+" \"TI\", "+" \"SI\", "+" \"AD\""+" ]"+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile","POST",payload);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/profile";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload={"name"=>"creation test","isDefault"=>false,"numSubaccount"=>0,"sharedGroups"=>["-4ERSngBaas466fasfdqQK-sPYG32341PqVx"],"sharedTemplates"=>[30],"sharedBlacklists"=>false,"enabledServices"=>["pages","sms","smsadv","richsms","email","rcp","sr"],"enabledSMSQualities"=>["GP","TI","SI","AD"]};$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On creation succes, the above is returned:
{"idSubaccountProfile":91213,"name":"creation test","enabledServices":["pages","sms","smsadv","richsms","email","rcp","sr"],"enabledSMSQualities":["GP","TI","SI","AD"],"numSubaccount":0,"sharedGroups":[{"id":"-4ERSngBaas466fasfdqQK-sPYG32341PqVx","name":"Test","description":"","groupType":0,"totalContactsCount":0,"sharingInfo":{"idSharing":41234,"idParentSharing":0,"idUserSharing":4123,"idUserResourceOwner":4123,"idSubaccountProfile":91213},"emailContactsCount":0}],"sharedTemplates":[{"idTemplate":30,"encoding":"GSM","name":"Model 02","text":"This is model for api docs","sender":null,"richUrl":null,"idPage":null,"sharingInfo":{"idSharing":454123,"idParentSharing":0,"idUserSharing":4123,"idUserResourceOwner":4123,"idSubaccountProfile":91213}}],"sharedBlacklists":[{"userOwnerId":4123,"sharingInfo":{"idSharing":46,"idParentSharing":0,"idUserSharing":4123,"idUserResourceOwner":4123,"idSubaccountProfile":91213}}],"isDefault":false}
Creates a new Subaccount profile.
HTTP request
POST /API/v1.0/REST/subaccount/profile
Body fields
The body must contain a Json with the following content:
Parameter
Type
Description
Required
Default
name
String
The name of the subaccount
Yes
isDefault
boolean
Tell whether or not this must be set as default account
Yes
numSubaccount
number
Limits the number of subaccount that can be created
Yes
sharedGroups
List(String)
Ids of the groups to be shared with the created subaccount. Can be an empty list
Yes
sharedTemplates
List(number)
Ids of the templates to share with the created subaccount. Can be an empty list
Yes
sharedBlacklists
boolean
Tell whether or not to share the owner and the owner’ shared blacklists
Yes
enabledServices
List(String)
The list of services to enable
Yes
enabledSMSQualities
List(String)
The list of sms qualities to enable
Yes
Returns
Code
Description
200
Successful request
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }payload="""{
"idSubaccountProfile": 92789,
"name": "test-test",
"isDefault": false,
"numSubaccount": 0,
"sharedGroups": [
"-4789ERSngBqQK-sPYGPqVx"
],
"sharedTemplates": [
30
],
"sharedBlacklists": true,
"enabledServices": [
"sms",
"pages",
"richsms"
],
"enabledSMSQualities": [
"GP",
"TI"
]
}"""r=requests.post("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id",headers=headers,data=payload)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"idSubaccountProfile\": 92789, "+" \"name\": \"test-test\", "+" \"isDefault\": false, "+" \"numSubaccount\": 0, "+" \"sharedGroups\": ["+" \"-4789ERSngBqQK-sPYGPqVx\""+" ], "+" \"sharedTemplates\": ["+" 30"+" ], "+" \"sharedBlacklists\": true, "+" \"enabledServices\": ["+" \"sms\", "+" \"pages\", "+" \"richsms\""+" ], "+" \"enabledSMSQualities\": ["+" \"GP\", "+" \"TI\""+" ]"+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "idSubaccountProfile": 92789, '.' "name": "test-test", '.' "isDefault": false, '.' "numSubaccount": 0, '.' "sharedGroups": ['.' "-4789ERSngBqQK-sPYGPqVx"'.' ], '.' "sharedTemplates": ['.' 30'.' ], '.' "sharedBlacklists": true, '.' "enabledServices": ['.' "sms", '.' "pages", '.' "richsms"'.' ], '.' "enabledSMSQualities": ['.' "GP", '.' "TI"'.' ]'.'}';$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: session_key',// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);$response=curl_exec($ch);$info=curl_getinfo($ch);curl_close($ch);if($info['http_code']!=200){echo('Error! http code: '.$info['http_code'].', body message: '.$response);}else{$obj=json_decode($response);print_r($obj);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id")payload={"idSubaccountProfile":92789,"name":"test-test","isDefault":false,"numSubaccount":0,"sharedGroups":["-4789ERSngBqQK-sPYGPqVx"],"sharedTemplates":[30],"sharedBlacklists":true,"enabledServices":["sms","pages","richsms"],"enabledSMSQualities":["GP","TI"]}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"idSubaccountProfile\": 92789, "+" \"name\": \"test-test\", "+" \"isDefault\": false, "+" \"numSubaccount\": 0, "+" \"sharedGroups\": ["+" \"-4789ERSngBqQK-sPYGPqVx\""+" ], "+" \"sharedTemplates\": ["+" 30"+" ], "+" \"sharedBlacklists\": true, "+" \"enabledServices\": ["+" \"sms\", "+" \"pages\", "+" \"richsms\""+" ], "+" \"enabledSMSQualities\": ["+" \"GP\", "+" \"TI\""+" ]"+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id","POST",payload);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload={"idSubaccountProfile"=>92789,"name"=>"test-test","isDefault"=>false,"numSubaccount"=>0,"sharedGroups"=>["-4789ERSngBqQK-sPYGPqVx"],"sharedTemplates"=>[30],"sharedBlacklists"=>true,"enabledServices"=>["sms","pages","richsms"],"enabledSMSQualities"=>["GP","TI"]};$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On update succes, the above is returned:
{"idSubaccountProfile":92789,"name":"test-test","enabledServices":["sms","pages","richsms"],"enabledSMSQualities":["GP","TI"],"numSubaccount":0,"sharedGroups":[{"id":"-4789ERSngBqQK-sPYGPqVx","name":"A-789","description":"","groupType":0,"totalContactsCount":0,"sharingInfo":{"idSharing":41789,"idParentSharing":0,"idUserSharing":4789,"idUserResourceOwner":4789,"idSubaccountProfile":92789},"emailContactsCount":0}],"sharedTemplates":[{"idTemplate":30,"encoding":"GSM-789","name":"Modello 02789","text":"This is 789 model","sender":null,"richUrl":null,"idPage":null,"sharingInfo":{"idSharing":42789,"idParentSharing":0,"idUserSharing":4789,"idUserResourceOwner":4789,"idSubaccountProfile":92789}}],"sharedBlacklists":[{"userOwnerId":4789,"sharingInfo":{"idSharing":43789,"idParentSharing":0,"idUserSharing":4789,"idUserResourceOwner":4789,"idSubaccountProfile":92789}}],"isDefault":false}
Updates the given Subaccount profile.
HTTP request
POST /API/v1.0/REST/subaccount/profile/profile_id
Body fields
The body must contain a Json with the following content:
Parameter
Type
Description
Required
Default
name
String
The name of the subaccount
Yes
isDefault
boolean
Tell whether or not this must be set as default account
Yes
numSubaccount
number
Limits the number of subaccount that can be created
Yes
sharedGroups
List(String)
Ids of the groups to be shared with the created subaccount. Can be an empty list
Yes
sharedTemplates
List(number)
Ids of the templates to share with the created subaccount. Can be an empty list
Yes
sharedBlacklists
boolean
Tell whether or not to share the owner and the owner’ shared blacklists
Yes
enabledServices
List(String)
The list of services to enable
Yes
enabledSMSQualities
List(String)
The list of sms qualities to enable
Yes
Returns
Code
Description
200
Successful request
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/profile";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
{"idSubaccountProfile":154321,"name":"default","enabledServices":["sms","email","sr"],"enabledSMSQualities":["GP","SI"],"numSubaccount":0,"sharedGroups":[{"id":"e4CeG3g4321BqQK-sPYG355x","name":"Example name","description":"","groupType":0,"totalContactsCount":0,"sharingInfo":{"idSharing":94321,"idParentSharing":0,"idUserSharing":44321,"idUserResourceOwner":44321,"idSubaccountProfile":154321},"emailContactsCount":0}],"sharedTemplates":[{"idTemplate":294321,"encoding":"GSM","name":"Model 4321","text":"Text for model 4321 test","sender":null,"richUrl":null,"idPage":null,"sharingInfo":{"idSharing":104321,"idParentSharing":0,"idUserSharing":44321,"idUserResourceOwner":44321,"idSubaccountProfile":154321}}],"sharedBlacklists":[],"isDefault":true}
Returns the data of the given SubaccountProfile ID.
HTTP request
GET /API/v1.0/REST/subaccount/profile/profile_id
Parameters
Parameter
Type
Description
Required
Default
profile_id
Int
The Profile ID
Yes
-
Returns
Code
Description
200
The requested Subaccount Profile data
400
Other errors, details are in the body
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.get("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Get.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringresponse=wb.DownloadString("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices");dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/activableServices";my$req=HTTP::Request->new(GET=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }r=requests.delete("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id",headers=headers)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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 responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: 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);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id")# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Delete.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");wb.UploadValues("https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id","DELETE",newNameValueCollection());dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/subaccount/profile/profile_id";my$req=HTTP::Request->new(DELETE=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }payload="""{
"recipient": "+443471234567"
}"""r=requests.post("https://api.textanywhere.com/API/v1.0/REST/2fa/request",headers=headers,data=payload)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/2fa/request");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"recipient\": \"+443471234567\""+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "recipient": "+443471234567"'.'}';$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/2fa/request');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: session_key',// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);$response=curl_exec($ch);$info=curl_getinfo($ch);curl_close($ch);if($info['http_code']!=200){echo('Error! http code: '.$info['http_code'].', body message: '.$response);}else{$obj=json_decode($response);print_r($obj);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/2fa/request")payload={"recipient":"+443471234567"}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"recipient\": \"+443471234567\""+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/2fa/request","POST",payload);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/2fa/request";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload={"recipient"=>"+443471234567"};$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
{"status":"OK"}
On failure, the above command returns the following response:
{"status":"ERROR","error":"Error cause"}
Request a Two Factor Authentication via text message.
This method generates a pin and sends it via text message to the user.
HTTP request
POST /API/v1.0/REST/2fa/request
Body fields
Parameter
Type
Description
Required
Default
recipient
String
The phone number of the user. The format must be +441234567890 or 00441234567890
Yes
-
senderName
String
The sender name or number for the text message
No
Preferred Sender Name
expiry
Integer
The expiration time of the PIN, in minutes
No
60
messageBody
String
The message body. PIN position in the text can be specified using the %PIN% placeholder. If the placeholder is not provided the pin will be added at the end of message body.
No
A default message body per language.
Returns
Code
Description
200
pin has been successfully sent via text message.
400
[Bad request] Invalid recipient, senderName, expiry, or sending errors like not enough credit.
401
[Unauthorized] User_key, Token or Session_key are invalid or not provided
# pip install requestsimportrequestsimportjsonfromrequests.authimportHTTPBasicAuth# Use this when using Session Key authenticationheaders={'user_key':'user_key','Session_key':'session_key','Content-type':'application/json'}# When using Access Token authentication, use this instead:# headers = { 'user_key': 'UserParam{user_key}', 'Access_token' : 'UserParam{access_token}', 'Content-type' : 'application/json' }payload="""{
"recipient": "+443471234567",
"pin": "12345"
}"""r=requests.post("https://api.textanywhere.com/API/v1.0/REST/2fa/verify",headers=headers,data=payload)ifr.status_code!=200:print("Error! http code: "+str(r.status_code)+", body message: "+str(r.content))else:response=r.textobj=json.loads(response)print(unicode(obj))
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.io.OutputStream;importjava.net.URL;importjava.util.Base64;publicclassMain{publicstaticvoidmain(String[]args){try{URLurl=newURL("https://api.textanywhere.com/API/v1.0/REST/2fa/verify");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestProperty("user_key","user_key");// Use this when using Session Key authenticationconn.setRequestProperty("Session_key","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);Stringpayload="{"+" \"recipient\": \"+443471234567\", "+" \"pin\": \"12345\""+"}";OutputStreamos=conn.getOutputStream();os.write(payload.getBytes());os.flush();if(conn.getResponseCode()!=200){// Print the possible error contained in body responseStringerror="";Stringoutput;BufferedReadererrorbuffer=newBufferedReader(newInputStreamReader(conn.getErrorStream(),"UTF-8"));while((output=errorbuffer.readLine())!=null){error+=output;}System.out.println("Error! HTTP error code : "+conn.getResponseCode()+", Body message : "+error);thrownewRuntimeException("Failed : HTTP error code : "+conn.getResponseCode());}BufferedReaderbr=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringresponse="";Stringoutput;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 responseGsonBuilderbuilder=newGsonBuilder();Gsongson=builder.create();MyObjectresponseObj=gson.fromJson(response,MyObject.class);conn.disconnect();}catch(Exceptione){e.printStackTrace();}}}
<?php$payload='{'.' "recipient": "+443471234567", '.' "pin": "12345"'.'}';$ch=curl_init();curl_setopt($ch,CURLOPT_URL,'https://api.textanywhere.com/API/v1.0/REST/2fa/verify');curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json','user_key: user_key',// Use this when using session key authentication
'Session_key: session_key',// When using Access Token authentication, use this instead:
// 'Access_token: UserParam{access_token}'
));curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);$response=curl_exec($ch);$info=curl_getinfo($ch);curl_close($ch);if($info['http_code']!=200){echo('Error! http code: '.$info['http_code'].', body message: '.$response);}else{$obj=json_decode($response);print_r($obj);}?>
require'net/http'require'uri'require'json'uri=URI.parse("https://api.textanywhere.com/API/v1.0/REST/2fa/verify")payload={"recipient":"+443471234567","pin":"12345"}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)http.use_ssl=truerequest=Net::HTTP::Post.new(uri.request_uri)request['Content-type']='application/json'request['user_key']='user_key'request['Session_key']='session_key'request.body=payload.to_json# Send the requestresponseData=http.request(request)ifresponseData.code=="200"response=responseData.bodyobj=JSON.parse(response)putsobjelseputs"Error! http code: "+responseData.code+", body message: "+responseData.bodyend
usingSystem;usingSystem.IO;usingSystem.Text;usingSystem.Net;usingSystem.Collections.Specialized;// We are using JSON.NET (http://www.newtonsoft.com/json)usingNewtonsoft.Json;/*
* The following code has been compiled and tested using the MONO
* project.
*
* To compile using MONO:
* mcs -r:Newtonsoft.Json.dll example.cs
*/namespaceRestApplication{classProgram{staticvoidMain(string[]args){using(varwb=newWebClient()){// 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","user_key");wb.Headers.Add("Session_key","session_key");Stringpayload="{"+" \"recipient\": \"+443471234567\", "+" \"pin\": \"12345\""+"}";Stringresponse=wb.UploadString("https://api.textanywhere.com/API/v1.0/REST/2fa/verify","POST",payload);dynamicobj=JsonConvert.DeserializeObject(response);Console.WriteLine(obj);}catch(WebExceptionex){varstatusCode=((HttpWebResponse)ex.Response).StatusCode;varerrorResponse=newStreamReader(ex.Response.GetResponseStream()).ReadToEnd();Console.WriteLine("Error!, http code: "+statusCode+", body message: ");Console.WriteLine(errorResponse);}}}}}
#!/usr/bin/env perlusewarnings;usestrict;useLWP::UserAgent;# Install using Cpan: "cpan JSON URI"useJSON;useURI::Escape;my$ua=LWP::UserAgent->new;my$server_endpoint="https://api.textanywhere.com/API/v1.0/REST/2fa/verify";my$req=HTTP::Request->new(POST=>$server_endpoint);$req->header('Content_type'=>'application/json');# IMPORTANT: Not adding the ':' before 'user_key' and# 'Session_key' will result in perl to automatically rewrite the# headers as 'User-Key' and 'Session-Key', which is not supported# by our API.$req->header(':user_key'=>$auth->[0],':Session_key'=>$auth->[1]);my$payload={"recipient"=>"+443471234567","pin"=>"12345"};$req->content(to_json($payload));my$resp=$ua->request($req);if($resp->is_success&&$resp->code==200){my$response=$resp->decoded_content;my$obj=from_json($response);}else{my$error=$resp->decoded_content;my$code=$resp->code;print"Error!, http code: $code, body message: $error ";}
On success, the above command returns the following response:
{"status":"OK"}
On wrong pin, the above command returns the following response: