Tropo is part of CiscoLearn More

REST POST and GET in each Scripting language

Here are some samples to hopefully get you started in situations where you need to send or retrieve information using REST:

PHP

POST:

$url = 'https://api.tropo.com/v1/applications';
$var = "name=New+App&platform=scripting&partition=staging";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD,"username:password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $var);

$response = curl_exec($ch);
print $response . "\n\n";
$request_header_info = curl_getinfo($ch, CURLINFO_HEADER_OUT);
print $request_header_info;
curl_close($ch);

GET

$token = 'your_token';
$curl_handle=curl_init();

curl_setopt($curl_handle,CURLOPT_URL,'http://api.tropo.com/1.0/sessions?action=create&token='.$token);

curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_exec($curl_handle);
curl_close($curl_handle);

Ruby

POST Example 1:

require 'net/http'
require 'uri'

url = URI.parse("https://api.tropo.com/v1/applications")

req = Net::HTTP::Post.new(url.path)
req.basic_auth 'username', 'password'
req.set_form_data({'name' => "hiiiiiiyah" , 'voiceUrl' => 'http://www.example.com/', 'messagingUrl' => 'http://www.example2.com/', 'platform' => 'webapi', 'partition' => 'production'})

sock = Net::HTTP.new(url.host, url.port)
sock.use_ssl = true
res = sock.start {|http| http.request(req) }

puts res.body

POST Example 2:

require 'net/http'
 
req = Net::HTTP::Post.new '/v1/applications'
req.basic_auth 'username', 'password'
req.set_form_data name: "hiiiiiiyah", voiceUrl: 'http://www.example.com/', messagingUrl: 'http://www.example2.com/', platform: 'webapi', partition: 'production'
 
res = Net::HTTP.start('api.tropo.com', '80', use_ssl: true) do |http|
http.request req
end
 
puts res.body

GET Example 1:

require 'net/http'
require 'uri'

token = 'your_token'
url = 'http://api.tropo.com/1.0/sessions?action=create&token='+token
response = Net::HTTP.get_print URI.parse(url)

GET Example 2:

require 'net/http'
 
puts Net::HTTP.get('http://api.tropo.com', '/1.0/sessions?action=create&token=your_token')

Javascript

POST

function post(url, options) {
    if(options.query) {
        url += "?";
        var delimiter = "";
        for(var propName in (options.query||{})) {
            url += (delemiter + (propName + "=" + escape(options.query[propName])));
            delimiter = "&";
        }
    }
    log("Fetching " + url);
    var code;

    var body = options.body;
    if(body == null) {
        throw {message:"Body is required"};
    }

    try {

        // Open Connection
        connection = new java.net.URL(url).openConnection();

        // Set timeout
        var timeout = options.timeout ? options.timeout : 10000;
        connection.setReadTimeout(timeout);
        connection.setConnectTimeout(timeout);

        // Method == POST
        connection.setRequestMethod("POST");

        // Set Content Type
        var contentType = options.contentType != null ? options.contentType : "text/plain";
        connection.setRequestProperty("Content-Type", contentType);

        // Set Content Length
        connection.setRequestProperty("Content-Length", body.length);

        // Silly Java Stuff
        connection.setUseCaches (false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send Post Data
        bodyWriter = new java.io.DataOutputStream(connection.getOutputStream());
        bodyWriter.writeBytes(body);
        bodyWriter.flush ();
        bodyWriter.close ();

        code = connection.getResponseCode();
    }
    catch(e) {
        throw {message:("Socket Exception or Server Timeout: " + e), code:0};
    }
    if(code < 200 || code > 299) {
        throw {message:("Received non-2XX response: " + code), code:code};
    }
    is = null;
    try {
        is = connection.getInputStream();
        return new String(org.apache.commons.io.IOUtils.toString(is));
    }
    catch(e) {
        throw {message:("Failed to read server response"), code:0};
    }
    finally {
        try {if(is != null)is.close();} catch (err){}
    }

}

post("http://www.postbin.org/n1izs5", {body : "Hello, Post Bin!"});

GET Example 1

var _conn;
var _cm;
var _chat;

function getFunny(channel,show){
    var ret = "http://downloads.bbc.co.uk/podcasts/radio4/fricomedy/fricomedy_20130111-1900a.mp3";

    importPackage(java.io, java.net, javax.xml.xpath, org.xml.sax);
        var rssUrl = "http://downloads.bbc.co.uk/podcasts/" + channel + "/" + show + "/rss.xml";
        log("RSS URL ="+rssUrl);
        var url = new URL(rssUrl);
        var urlStream = url.openStream();

        var paths = "/rss/channel/item/link";
        var ips = new InputSource(urlStream);
        var xPath = XPathFactory.newInstance().newXPath();
        ret = xPath.evaluate(paths, ips);

    return ret;
}

GET Example 2

function load_app(url){

    connection = new java.net.URL(url).openConnection();
    connection.setDoOutput(false);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", "text/plain");
    connection.setRequestProperty("charset", "utf-8");
    connection.connect();

    dis = new java.io.DataInputStream(connection.getInputStream());
    while (dis.available() != 0) {
        line = dis.readLine();
        this.eval(""+line);
    } 
}

load_app("https://raw.github.com/gist/47f48bc1420cb385e0ed/7d83c979de3673083ad45663e3f98fd1caf545ea/gistfile1.txt");
load_app("https://raw.github.com/gist/b433558b21e165107e99/14f61963b97c52af3c860f28ef8ebea68de0efe7/gistfile1.txt");

Python

POST

import urllib
import urllib2

url = 'https://api.tropo.com/v1/applications'
username = ''
password = ''


passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)

values = {
    "name":"Python works 2!",
    "voiceUrl":"http://website.com",
    "messagingUrl":"http://website2.com",
    "platform":"scripting",
    "partition":"staging"
}

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()

print the_page

GET

import urllib
import urllib2

token = 'token'
f = urllib2.urlopen('http://api.tropo.com/1.0/sessions?action=create&token='+token)
data = f.read()
f.close()

Groovy

GET & POST

class GroovyHTTP {
  public method='POST'
  public uri
  public host
  public path
  public port
  public params=null
  public socket=null
  public writer=null
  public reader=null
  public writedata
  public headers = []
  public content

  // set the url and create new URI object
  def GroovyHTTP(url) {
    uri = new URI(url)
    host = uri.getHost()
    path = uri.getRawPath() 
    port = uri.getPort() 
    def tpar = uri.getQuery()
    if(tpar != null && tpar != '') {
      tpar.tokenize('&').each{
        def pp = it.tokenize('=');
        this.setParam(pp[0],pp[1]);
      }
    } 
    if(port == null || port < 0) port = 80
    if(path == null || path.length() == 0) path = "/"     
  }

  // sets the method (GET or POST)
  def setMethod(setmethod) {
    method = setmethod
  }

  // push params into this request
  def setParam(var,value) {
    if(params != null) 
      params += '&'
    else
      params=''
    params += var +'='+URLEncoder.encode(value) 
  }

  // clear params
  def clearParams() {
    params = null
  }

  // open a new socket
  def open() { 
    socket = new Socket(host, port)
  }

  // write data to the socket
  def write() { 
    def contentLen = 0
    if(params!=null) contentLen = params.length() 
    def writedata = '';

    if(this.method == 'GET')   
      writedata += "GET " + path +'?'+ params + " HTTP/1.0\r\n"
    else
      writedata += "POST " + path + " HTTP/1.0\r\n"

    writedata +=
      "Host: " + host + "\r\n" + 
      "Content-Type: application/x-www-form-urlencoded\r\n" + 
      "Content-Length: " + contentLen + "\r\n\r\n" + 
      params + "\r\n"
      "Connection: close\r\n\r\n"  

    writer = new PrintWriter(socket.getOutputStream(), true)
    writer.write(writedata)
    writer.flush() 
  }

  // read response from the server
  def read() { 
    reader = new DataInputStream(socket.getInputStream())
    def c = null
    while (null != ((c = reader.readLine()))) {   
      if(c=='') break 
      headers.add(c)   
    } 
  } 

  // get header value by name
  def getHeader(name) {
    def pattern = name + ': ' 
    def result
    headers.each{ 
      if(it ==~ /${pattern}.*/) { 
        result = it.replace(pattern,'').trim()
        return 2
      }   
    }
    return result
  }

  // get the response content
  def getContent() { 
    def row 
    content = ''
    while (null != ((row = reader.readLine()))) content += row + "\r\n"  
    return content = content.trim();
  }

  // close the socket
  def close() {
    reader.close() 
    writer.close()
    socket.close()
  }
}

h = new GroovyHTTP('http://requestb.in/qwkm8sqw')     
h.setMethod('POST') 
h.setParam('q', 'groovy')
h.setParam('test1', 'This is a test')
h.setParam('test2', 'This is actually working')
h.setParam('test3', 'Kevin Bond!')
h.open()
h.write()
h.read() 
println h.getHeader('Server')  
println h.getContent() 
h.close()