25 November, 2016

API Instructions

Our API is RESTful. You call a URL on our server and we return JSON.

Making requests
Once you get your API key you can test the API straight away in your browser: Visit:
https://api.aimining.com/emowatch/v1?input=Hello&key=YOURAPIKEY

This will return something like:

{
    "status": "200", 
    "meta": {
        "generated": "2016-11-28 12:31:23", 
        "timetaken": 4, 
        "maxwordsperinput": 25, 
        "maxinputs": 10, 
    }, 
    "inputs": [
        {
            "input": "Hello", 
            "processedinput": "hello",
            "numwords": 1,
            "classes": {
                "love": "0.4485", 
                "wow": "0.0740", 
                "haha": "0.0244", 
                "sad": "0.3250", 
                "angry": "0.1281"
            }
        }
    ]
}

API URL
The URL you call will always start with https://api.aimining.com/. We only accept secure https requests.

This is followed by the name of the product and a version number. We currently offer Emowatch for emotion analysis and Sentwatch for sentiment analysis, both in version 1. So the full URL will be one of:

https://api.aimining.com/emowatch/v1
https://api.aimining.com/sentwatch/v1

Your API key can be used for either product.

Parameters
The API accepts several URL parameters. Most important is the input which contains the text you want to analyse. Our API allows you to pass in multiple inputs at once (but it still only counts as one API call). The input is required. Without it, you will get a 503 error. For example:

  • input=hello&input=hola
  • input[]=hello&input[]=hola – this is how languages like PHP pass arrays in URLs

Along with the input, you also need to pass in your API key with the key parameter. The key is required. Without it you will get a 401 (unauthorised) error.

You can also pass in an optional callback parameter for JSONP requests, which will wrap the JSON object. For example, this URL:

https://api.aimining.com/emowatch/v1?input=hello&input=How+are+you%3F&callback=ProcessReply&key=YOURAPIKEY

Will return the object above wrapped in a call to a ProcessReply function:

ProcessReply ({ ...})

Notice that the results above are all indented and easily readable. This is the default behaviour (based on reading lots about how to design an easy-to-use API) but you can disable it by passing indent=no. This turns off indenting so that all the JSON will come back as a single line.

Finally you can pass in flow=yes, which will show the emotional or sentiment values after each word in the input. This will add a flow array to each input in the JSON. For example the following URL returns 3 elements on the flow array for the sub sentences “how”, “how are” and “how are you”. The last element in the flow array will be the same as the classes object.

https://api.aimining.com/sentwatch/v1?input=You+are+great&flow=yes&key=YOURAPIKEY

            "flow": [
                {
                    "negative": "0.2627", 
                    "positive": "0.7373"
                }, 
                {
                    "negative": "0.1836", 
                    "positive": "0.8164"
                }, 
                {
                    "negative": "0.0582", 
                    "positive": "0.9418"
                }
            ]

The API also accepts the input parameter via POST. This is necessary for very long requests (see below). The other parameters such as key should still be sent as part of the URL and not within the POST body.

Format of the JSON Data

The JSON reply includes:

  • the HTTP status of the reply, described below
  • description of the error for invalid requests with status other than 200
  • meta data, described below
  • an inputs array, with one entry corresponding to each input sent, described below

The meta data includes:

  • the date this reply was generated (it could come from cache)
  • the server time taken in milliseconds
  • the maximum number of words accepted per input, if too many are provided the beginning will be truncated
  • the maximum number of inputs accepted

Each input is represented as an object containing:

  • the actual input passed in, for example “Hello” in this case
  • the processed input showing the text actually passed into the model, depending on the model it might be in lower case or include <unknown> words
  • a classes object with the results between 0 and 1 for each class, always adding up to 1. The Emowatch classes are: love, haha, wow, sad and angry. Sentwatch returns: positive and negative.
  • if requested, a flow array containing the emotional results after each word in the input

Status codes:

  • 200: valid API request
  • 401: unauthorised due to missing or invalid API key
  • 404: API not found, URL must start with one of our products like /emowatch/v1
  • 413: request too large if you send a GET request over 16Kb long, in this case POST the input instead
  • 502 or 504: unable to get reply from API server, please contact us
  • 503: too many requests from a single IP address or API key

Any non-valid requests will return only status and error, but still as valid JSON.

Using the API
Our API returns results in JSON format. Using PHP, a call to our API would look like:

<?php
$url = "https://api.aimining.com/emowatch/v1";
$key = "YOURAPIKEY";
$input = rawurlencode ("How are you?");
$apidata = json_decode (file_get_contents ("$url?input=$input&key=$key"));
?>

Or you can use Javascript and pass in a callback parameter. The following code snippet creates a <script> tag referencing our API. When the API returns the results, they will be passed to the ProcessReply function which will tell you the proportion of love:

<script>
url = "https://api.aimining.com/emowatch/v1";
key = "YOURAPIKEY";
input = encodeURIComponent ("How are you?");
function ProcessReply (data) {
    if (data.error) console.log ('Error: ' + data.error);
    else alert ('Love: ' + data.inputs[0].classes.love);
}
script_element = document.createElement('script'); //create new script element
script_element.src = url + "?input=" + input + '&key=' + key + '&callback=ProcessReply';
document.getElementsByTagName ('head')[0].appendChild(script_element); //append to page, which executes it
</script>

The last three lines are much easier to read using jQuery:

<script>
$.ajax({
    url: url,
    data: {"input": input, "key": key}, //input automatically encoded
    dataType: "jsonp",
    success: ProcessReply
});
</script>

Please note that putting your API key inside a Javascript file like this is not recommended on public websites. Your API key could be easily used by someone else. So for public websites we recommend making calls on the server-side using a language like Python or PHP.

Our own demos are mostly written in Javascript to show nice charts. We make server-side PHP calls to the API and embed the returned JSON directly into the page, using indent=no so all the JSON is on one line:

<?php
$url = "https://api.aimining.com/emowatch/v1";
$key = "YOURAPIKEY";
$input = rawurlencode ("How are you?");
echo "<script>ProcessReply (" . file_get_contents ("$url?input=$input&key=$key&indent=no") . ")</script>";
?>

Actually, all our demos use a small PHP function which switches to POST if the request is too long, and also ensures that error messages are returned properly by file_get_contents. It looks like this:

<?php   

function AiminingCallProxy ($proxy, $input, $flow=false) {
        $url = "https://api.aimining.com/$proxy"; //API url
        $key = "YOURAPIKEY"; //the API key
        $url .= "?key=$key" . ($flow ? '&flow=yes' : '') . "&indent=no"; //the query string 
        if (!is_array ($input)) $input = array ($input); //$input can be array or string
        foreach ($input as $i=>$t) $input[$i] = 'input[]=' . rawurlencode ($t);
        $allinput = join ('&', $input); //all input joined together
        $opts = array ('ignore_errors' => true); //options to pass into the context
        if (strlen ($allinput) <= 2000) $url .= "&$allinput"; //GET if a smallish request
        else { //make a POST
                $opts['method']='POST';
                $opts['header']='Content-type: application/x-www-form-urlencoded';
                $opts['content']=$allinput;
        }
        $r = file_get_contents ("$url", false, stream_context_create (array ('http'=>$opts)));
        return $r;
}

$input = "How are you?";
echo "<script>ProcessReply (" . AiminingCallProxy ('/emowatch/v1', $input) . ")</script>";
?>

Charging
Access to our API is provided on a monthly basis, with the first month free, starting on the day you make your order. Each call to one of our API URLs containing your key counts as one API call, even if you pass in multiple inputs and request the emotional flow. If you approach your monthly limit, we will contact you to let you know. See our FAQ for more information.