<div id="api_guide">
  <h2>Getting started with the Kidney REST API</h2>

  <p>This page describes the basics of using the kidney exchange REST API</p>

  <div id="rest_contents">
    <h3>Table of Contents</h3>
    <ul>
      <li><a href="#rest_quick_start">Quick Start</a></li>
      <li><a href="#rest_request">REST Requests</a></li>
      <li><a href="#rest_response">REST Responses</a></li>
      <li><a href="#rest_using">API Guide</a>
        <ul>
          <li><a href="#find_nhsbt"><code>find.xml</code></a></li>
          <li><a href="#find"><code>find.json</code></a></li>
        </ul>
      </li>
    </ul>
  </div>

  <div id="rest_quick_start">
    <h3>Quick Start</h3>
    <p>
      In addition to the <%= link_to 'SOAP API', {:action => 'soap'} %> the Kidney Exchange Allocator also exposes a
      REST-like API - there is no strict sense of resources, it's just essentially an API over HTTP. The API makes
      available two methods, <a href="#find.json"><code>find.json</code></a> and
      <a href="#find.xml"><code>find.xml</code></a>, both of which find an allocation of donors to patients with the
      output data being formatted in JSON and XML respectively.
    </p>

    <p>There are many libraries available in most programming languages to consume such a service; they vary from
    full blown REST resource kits to simple HTTP client libraries. Here we use the
     <a href="http://hc.apache.org/httpcomponents-client-ga/index.html">Apache Java HttpClient library</a>
     to show how the service can be used and the output data processed.</p>

    <p>First you will need to download the <a href="http://hc.apache.org/downloads.cgi">appropriate jar files</a>
      from the Apache website. On this page select 'binaries with dependencies' to get a superset of the jar files
      required to run this example - of these files you only really need the httpclient, httpcore and the common-logging
      jar files. The sample code below simply builds a URL to the service and sends this data using an HTTP POST
      request. It's worth noting that this must be a POST request and an error will be returned should you try to access
      this API with any other HTTP request type (e.g. GET or PUT). In the example below we are calling the
      <a href="#find.json"><code>find.json</code></a> method and as such the output data (also shown below) is returned
      in JSON format - more detailed information is available about the format on the
      <%= link_to 'Output Formats', {:action => 'output_format', :anchor => 'json'} %> page.</p>

    <pre class="brush: java">
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.net.URISyntaxException;

import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

public class Client {
    public static void main(String[] args) throws IOException, URISyntaxException {

      String data = "{ \"data\" :"
        + "{ \"1\" : { \"sources\" : [1],"
        +             "\"dage\" : 65,"
        +             "\"matches\" : [ { \"recipient\" : 2, \"score\" : 3},"
        +                             "{ \"recipient\" : 3, \"score\" : 1},"
        +                             "{ \"recipient\" : 4, \"score\" : 2} ]},"
        +   "\"2\" : { \"sources\" : [2],"
        +             "\"dage\" : 45,"
        +             "\"matches\" : [ { \"recipient\" : 1, \"score\" : 2},"
        +							                 "{ \"recipient\" : 5, \"score\" : 1} ]},"
        + "\"3\" : { \"sources\" : [3],"
        +           "\"dage\" : 25,"
        +           "\"matches\" : [ { \"recipient\" : 1, \"score\" : 1} ]},"
        + "\"4\" : { \"sources\" : [4],"
        +           "\"dage\" : 55,"
        +           "\"matches\" : [ { \"recipient\" : 2, \"score\" : 3},"
        +                           "{ \"recipient\" : 3, \"score\" : 2},"
        +                           "{ \"recipient\" : 5, \"score\" : 4} ]},"
        + "\"5\" : { \"sources\" : [5],"
        +           "\"dage\" : 30,"
        +           "\"matches\" : [ { \"recipient\" : 2, \"score\" :	1},"
        +                           "{ \"recipient\" : 4, \"score\" : 2} ]} } }";

    List&lt;NameValuePair&gt; qparams = new ArrayList&lt;NameValuePair&gt;();
    qparams.add(new BasicNameValuePair("data", data));
    qparams.add(new BasicNameValuePair("operation", "optimal"));
    qparams.add(new BasicNameValuePair("altruistic_chain_length", "1"));

    URI uri = URIUtils.createURI("http", "<%= "#{request.env['HTTP_HOST']}" %>", -1, "/kidney/find.json",
                                 URLEncodedUtils.format(qparams, "UTF-8"), null);
    HttpPost httpost = new HttpPost(uri);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
         InputStream instream = entity.getContent();
         BufferedReader reader = new BufferedReader(new InputStreamReader(instream));

         String str;
         while ((str = reader.readLine()) != null) {
          System.out.println(str);
         }
       }

      httpclient.getConnectionManager().shutdown();
  }
}
    </pre>
    <pre class="brush: js">
{ "algorithm" : "Optimal set of exchanges with respect to the optimality criteria",
  "output" : {
    "all_cycles": {
      "0": {"cycle": [{"p": 1,"d": 1,"tb": 0.025,"dif": 3,"s": 3},
                      {"p": 2,"d": 2,"tb": 0.025,"dif": 3,"s": 2}],
            "backarcs": 0, "weight": 11.05, "alt": []},
      "1": {"cycle": [{"p": 1,"d": 1,"tb": 0.009,"dif": 0,"s": 1},
                      {"p": 3,"d": 3,"tb": 0.009,"dif": 0,"s": 1}],
            "backarcs": 0, "weight": 2.018, "alt": []},
      "2": {"cycle": [{"p": 2,"d": 2,"tb": 0.03025,"dif": 3,"s": 1},
                      {"p": 5,"d": 5,"tb": 0.03025,"dif": 3,"s": 1}],
            "backarcs": 0, "weight": 8.0605, "alt": []},
      "3": {"cycle": [{"p": 4,"d": 4,"tb": 0.02025,"dif": 0,"s": 4},
                      {"p": 5,"d": 5,"tb": 0.02025,"dif": 0,"s": 2}],
            "backarcs": 0, "weight": 6.0405, "alt": []},
      "4": {"cycle": [{"p": 1,"d": 1,"tb": 0.036,"dif": 3,"s": 2},
                      {"p": 4,"d": 4,"tb": 0.036,"dif": 3,"s": 3},
                      {"p": 2,"d": 2,"b": 0,"tb": 0.025,"dif": 3,"s": 2}],
            "backarcs": 1, "weight": 16.097, "alt": []},
      "5": {"cycle": [{"p": 1,"d": 1,"tb": 0.036,"dif": 3,"s": 2},
                      {"p": 4,"d": 4,"tb": 0.016,"dif": 0,"s": 2},
                      {"p": 3,"d": 3,"b": 1,"tb": 0.009,"dif": 0,"s": 1}],
            "backarcs": 1, "weight": 8.061, "alt": []},
      "6": {"cycle": [{"p": 2,"d": 2,"b": 2,"tb": 0.03025,"dif": 3,"s": 1},
                      {"p": 5,"d": 5,"b": 3,"tb": 0.02025,"dif": 0,"s": 2},
                      {"p": 4,"d": 4,"tb": 0.036,"dif": 3,"s": 3}],
            "backarcs": 2, "weight": 12.0865, "alt": []}},
    "exchange_data": [
      { "description": "(COIN) Optimal set of exchanges",
        "exchanges": [1,6],
        "weight": 14.1045,
        "two_way_exchanges": 1,
        "total_transplants": 5,
        "three_way_exchanges": 1 } ]
  }
}
</pre>
  </div>

  <div id="rest_request">
    <h3>REST Requests</h3>
    <p>REST is the simplest request format to use - it's a simple HTTP POST action.

      The REST Endpoint URL is <code><%= "http://#{request.env['HTTP_HOST']}/kidney" %></code>
    </p>
  </div>

  <div id="rest_response">
    <h3>REST Response</h3>
    <p>REST is the simplest response format to use - it's a simple XML or JSON block depending on what format
      you have requested

      For XML the format will look something like this:

      <pre class="brush: xml">
        &lt;?xml version="1.0" encoding="utf-8" ?&gt;
        &lt;data&gt;
          &lt;algorithm&gt;
            [algorithm-name-here]
          &lt;/algorithm&gt;
          &lt;output&gt;
            [xml-payload-here]
          &lt;/output&gt;
        &lt;/data&gt;
      </pre>

      And for JSON it's something like this:
     <pre class="brush: js">
       { "algorithm" : [algorithm-name-here],
         "output" : [json-payload-here] }
     </pre>

    If an error occurs, and XML format is being used, the following is returned:
    <pre class="brush: xml">
      &lt;?xml version="1.0" encoding="utf-8" ?&gt;
      &lt;data&gt;
        &lt;algorithm&gt;
          [algorithm-name-here]
        &lt;algorithm&gt;
        &lt;error&gt;
          [error-message-here]
        &lt;error&gt;
      &lt;/data&gt;
    </pre>

    Similarly if an error occurs when using json we get:
    <pre class="brush: js">
      { "algorithm" : [algorithm-name-here],
        "output" : [error-message-here] }
    </pre>

  </div>

  <div id="rest_using">
    <h3>API Guide</h3>
    <p>The REST API exposes two methods, namely <a href="#find.xml"><code>find.xml</code></a> and
    <a href="#find.json"><code>find.json</code></a>. As you may expect these methods carry out the same operation
    and differ only in the format of the data they returned. Each method is discussed in detail below.</p>

    <div id="methods">
      <%= render :partial => 'find_template', :locals => {:out_format => 'JSON', :method_name => 'find.json'} %>
      <%= render :partial => 'find_template', :locals => {:out_format => 'XML', :method_name => 'find.xml'} %>
    </div>
  </div>
</div>