Getting up and running is easy!


Step 1.

Sign up for a free account


Step 2. 

Grab your API Key and Application ID from your email


Step 3.

Call the API

AYLIEN Text Analysis API is a package of eight different Natural Language Processing, Information Retrieval and Machine Learning APIs that can be quickly and easily adapted to your processes and applications. The Text Analysis API conforms to representational state transfer (REST) principles and can be used in any environment capable of making HTTP requests, including Java/JVM, Node.js, PHP, Python, Objective-C, Ruby and .NET.

Calling the API

Below we have provided SDKs and code samples for various languages to help you get started with your chosen language and integrate AYLIEN Text Analysis API into your app. The examples below demonstrate how to perform some basic Text Analysis functions in a variety of programming languages.

We have also built a Sandbox environment which makes it super easy to get up and running with the API.

Notes

  • All API requests go to https://api.aylien.com/.
  • The /api/v1/ part of the URI is the API version.
  • By default, API returns JSON, however, you can ask for the XML representation by means of content negotiation (Accept: text/xml).
  • The complete list of API endpoints and request parameters are available on our docs page.
  • In this example, in order to keep it succinct, we have left out error checking.
  • No external libraries are used in the examples to allow the example to be run independently.

SDKs and Code Snippets:

<?php
define('APPLICATION_ID',    YOUR_APP_ID);
define('APPLICATION_KEY',   YOUR_APP_KEY);

function call_api($endpoint, $parameters) {
  $ch = curl_init('https://api.aylien.com/api/v1/' . $endpoint);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json',
    'X-AYLIEN-TextAPI-Application-Key: ' . APPLICATION_KEY,
    'X-AYLIEN-TextAPI-Application-ID: '. APPLICATION_ID
  ));
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
  $response = curl_exec($ch);
  return json_decode($response);
}

$params = array('text' => 'John is a very good football player!');
$sentiment = call_api('sentiment', $params);
$language = call_api('language', $params);

echo sprintf("Sentiment: %s (%F)", $sentiment->polarity, $sentiment->polarity_confidence),
  PHP_EOL;
echo sprintf("Language: %s (%F)", $language->lang, $language->confidence),
  PHP_EOL;
?>
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.InputSource;
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

class Language {
  private String lang;
  private Double confidence;

  public String getLang() {
    return lang;
  }
  public void setLang(String lang) {
    this.lang = lang;
  }
  public Double getConfidence() {
    return confidence;
  }
  public void setConfidence(Double confidence) {
    this.confidence = confidence;
  }
}

class Sentiment {
  private String polarity;
  private Double polarityConfidence;

  public String getPolarity() {
    return polarity;
  }
  public void setPolarity(String polarity) {
    this.polarity = polarity;
  }

  public Double getPolarityConfidence() {
    return polarityConfidence;
  }
  public void setPolarityConfidence(Double confidence) {
    this.polarityConfidence = confidence;
  }
}

class TextAPISample {
  private static final String APPLICATION_ID = YOUR_APP_ID;
  private static final String APPLICATION_KEY = YOUR_APP_KEY;

  public static void main(String[] args) {
    String text = "John is a very good football player!";
    Language lang = getLanguage(text);
    System.out.printf("Language: %s (%f)\n",
        lang.getLang(), lang.getConfidence());
    Sentiment sent = getSentiment(text);
    System.out.printf("Sentiment: %s (%f)\n",
        sent.getPolarity(), sent.getPolarityConfidence());
  }

  public static Language getLanguage(String text) {
    final Map<String, String> parameters;
    parameters = new HashMap<String, String>();
    parameters.put("text", text);
    Document doc = callAPI("language", parameters);
    Language language = new Language();
    NodeList nodeList = doc.getElementsByTagName("lang");
    Node langNode = nodeList.item(0);
    nodeList = doc.getElementsByTagName("confidence");
    Node confNode = nodeList.item(0);
    language.setLang(langNode.getTextContent());
    language.setConfidence(Double.parseDouble(confNode.getTextContent()));

    return language;
  }

  public static Sentiment getSentiment(String text) {
    final Map<String, String> parameters;
    parameters = new HashMap<String, String>();
    parameters.put("text", text);
    Document doc = callAPI("sentiment", parameters);
    Sentiment sentiment = new Sentiment();
    NodeList nodeList = doc.getElementsByTagName("polarity");
    Node polarityNode = nodeList.item(0);
    nodeList = doc.getElementsByTagName("polarity_confidence");
    Node confNode = nodeList.item(0);
    sentiment.setPolarity(polarityNode.getTextContent());
    sentiment.setPolarityConfidence(Double.parseDouble(confNode.getTextContent()));

    return sentiment;
  }

  public static Document callAPI(String endpoint, Map<String, String> parameters) {
    URL url;
    HttpURLConnection connection = null;

    try {
      String queryString = "";
      StringBuilder sb = new StringBuilder();
      for (Map.Entry<String, String> e: parameters.entrySet()) {
        if (sb.length() > 0) { sb.append('&'); }
        sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=')
          .append(URLEncoder.encode(e.getValue(), "UTF-8"));
      }
      queryString = sb.toString();
      url = new URL("https://api.aylien.com/api/v1/" + endpoint);
      connection = (HttpURLConnection)url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty(
          "Content-Type", "application/x-www-form-urlencoded");
      connection.setRequestProperty(
          "Content-Length", Integer.toString(queryString.getBytes().length));
      connection.setRequestProperty("Accept", "text/xml");
      connection.setRequestProperty(
          "X-AYLIEN-TextAPI-Application-ID", APPLICATION_ID);
      connection.setRequestProperty(
          "X-AYLIEN-TextAPI-Application-Key", APPLICATION_KEY);
      connection.setDoInput(true);
      connection.setDoOutput(true);

      DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
      dos.writeBytes(queryString);
      dos.flush();
      dos.close();

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      InputSource xis = new InputSource(connection.getInputStream());

      return builder.parse(xis);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
    }
  }
}
var https = require('https'),
    querystring = require('querystring');

const APPLICATION_KEY = YOUR_APP_KEY,
      APPLICATION_ID = YOUR_APP_ID;

function call_api(endpoint, parameters, callback) {
  var postData = querystring.stringify(parameters);
  var request = https.request({
    host: 'api.aylien.com',
    path: '/api/v1/' + endpoint,
    headers: {
      'Accept':                             'application/json',
      'Content-Type':                       'application/x-www-form-urlencoded',
      'Content-Length':                     postData.length,
      'X-AYLIEN-TextAPI-Application-ID':    APPLICATION_ID,
      'X-AYLIEN-TextAPI-Application-Key':   APPLICATION_KEY,
    }
  }, function(response) {
    var data = "";
    response.on('data', function(chunk) {
      data += chunk;
    });
    response.on('end', function() {
      callback(JSON.parse(data));
    });
  });
  request.write(postData);
  request.end();
}

var parameters = {'text': 'John is a very good football player!'};
call_api('sentiment', parameters, function(result) {
  console.log(result);
});

call_api('language', parameters, function(result) {
  console.log(result);
});
import json
import urllib
import urllib2

APPLICATION_ID = YOUR_APP_ID
APPLICATION_KEY = YOUR_APP_KEY

def call_api(endpoint, parameters):
  url = 'https://api.aylien.com/api/v1/' + endpoint
  headers = {
      "Accept":                             "application/json",
      "Content-type":                       "application/x-www-form-urlencoded",
      "X-AYLIEN-TextAPI-Application-ID":    APPLICATION_ID,
      "X-AYLIEN-TextAPI-Application-Key":   APPLICATION_KEY
  }
  opener = urllib2.build_opener()
  request = urllib2.Request(url, urllib.urlencode(parameters), headers)
  response = opener.open(request);
  return json.loads(response.read())

parameters = {"text": "John is a very good football player!"}

sentiment = call_api("sentiment", parameters)
language = call_api("language", parameters)

print "Sentiment: %s (%F)" % (sentiment["polarity"], sentiment["polarity_confidence"])
print "Language: %s (%F)" % (language["lang"], language["confidence"])
Python 3
import json
import urllib.request, urllib.error, urllib.parse

APPLICATION_ID = YOUR_APP_ID
APPLICATION_KEY = YOUR_APP_KEY

def call_api(endpoint, parameters):
  url = 'https://api.aylien.com/api/v1/' + endpoint
  headers = {
      "Accept":                             "application/json",
      "Content-type":                       "application/x-www-form-urlencoded",
      "X-AYLIEN-TextAPI-Application-ID":    APPLICATION_ID,
      "X-AYLIEN-TextAPI-Application-Key":   APPLICATION_KEY
  }
  opener = urllib.request.build_opener()
  request = urllib.request.Request(url,
    urllib.parse.urlencode(parameters).encode('utf-8'), headers)
  response = opener.open(request);
  return json.loads(response.read().decode())

parameters = {"text": "John is a very good football player!"}

sentiment = call_api("sentiment", parameters)
language = call_api("language", parameters)

print("Sentiment: %s (%F)" % (sentiment["polarity"], sentiment["polarity_confidence"]))
print("Language: %s (%F)" % (language["lang"], language["confidence"]))
require 'net/http'
require 'uri'
require 'json'

APPLICATION_ID = YOUR_APP_ID
APPLICATION_KEY = YOUR_APP_KEY

def call_api(endpoint, parameters)
  url = URI.parse("https://api.aylien.com/api/v1/#{endpoint}")
  headers = {
      "Accept"                           =>   "application/json",
      "X-AYLIEN-TextAPI-Application-ID"  =>   APPLICATION_ID,
      "X-AYLIEN-TextAPI-Application-Key" =>   APPLICATION_KEY
  }

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(url.request_uri)
  request.initialize_http_header(headers)
  request.set_form_data(parameters)

  response = http.request(request)

  JSON.parse response.body
end

parameters = {"text" => "John is a very good football player!"}

sentiment = call_api("sentiment", parameters)
language = call_api("language", parameters)

puts "Sentiment: #{sentiment["polarity"]} (#{sentiment["polarity_confidence"]})"
puts "Language: #{language["lang"]} (#{language["confidence"]})"
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "strings"
)

const (
    APPLICATION_ID  = YOUR_APP_ID
    APPLICATION_KEY = YOUR_APP_KEY
)

type Sentiment struct {
    Text                   string  `json:"text"`
    Polarity               string  `json:"polarity"`
    Subjectivity           string  `json:"subjectivity"`
    PolarityConfidence     float64 `json:"polarity_confidence"`
    SubjectivityConfidence float64 `json:"subjectivity_confidence"`
}

type Language struct {
    Lang       string
    Confidence float32
}

func call_api(endpoint string, parameters url.Values) ([]byte, error) {
    client := &http.Client{}
    req, err := http.NewRequest("POST", "https://api.aylien.com/api/v1/"+endpoint,
        strings.NewReader(parameters.Encode()))
    if err != nil {
        return nil, err
    }
    req.Header.Add("Accept", "application/json")
    req.Header.Add("Content-type", "application/x-www-form-urlencoded")
    req.Header.Add("X-AYLIEN-TextAPI-Application-ID", APPLICATION_ID)
    req.Header.Add("X-AYLIEN-TextAPI-Application-Key", APPLICATION_KEY)
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }
    return body, err
}

func sentiment(text string) (Sentiment, error) {
    var sen Sentiment
    var params = url.Values{}
    params.Add("text", text)
    resp, err := call_api("sentiment", params)
    if err != nil {
        return sen, err
    }
    err = json.Unmarshal(resp, &sen)
    if err != nil {
        return sen, err
    }

    return sen, nil
}

func language(text string) (Language, error) {
    var lang Language
    var params = url.Values{}
    params.Add("text", text)
    resp, err := call_api("language", params)
    if err != nil {
        return lang, err
    }
    err = json.Unmarshal(resp, &lang)
    if err != nil {
        return lang, err
    }

    return lang, nil
}

func main() {
    text := "John is a very good football player!"
    s, err := sentiment(text)
    if err == nil {
        fmt.Printf("Sentiment: %s (%f)\n", s.Polarity, s.PolarityConfidence)
    }
    l, err := language(text)
    if err == nil {
        fmt.Printf("Language: %s (%f)\n", l.Lang, l.Confidence)
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace AylienTextAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic parameters = new System.Dynamic.ExpandoObject();
            parameters.text = "John is a very good football player!";

            var sentiment = CallApi("sentiment", parameters);
            var language = CallApi("language", parameters);

            Console.WriteLine("Sentiment: {0} ({1})",
                sentiment["polarity"], sentiment["polarity_confidence"]);
            Console.WriteLine("Language: {0} ({1})",
                language["lang"], language["confidence"]);
        }

        private static dynamic CallApi(String endpoint, dynamic parameters)
        {
            String APPLICATION_ID = YOUR_APP_ID;
            String APPLICATION_KEY = YOUR_APP_KEY;
            Uri address = new Uri("https://api.aylien.com/api/v1/" +
                endpoint);

            // Create the web request
            HttpWebRequest request = WebRequest.Create(address) as
                HttpWebRequest;

            // Set type to POST
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            // Create the data we want to send
            StringBuilder data = new StringBuilder();
            var i = 0;
            foreach (var item in parameters)
            {
                if (i == 0)
                    data.Append(item.Key + "=" +
                        HttpUtility.UrlEncode(item.Value));
                else
                    data.Append("&" + item.Key + "=" +
                        HttpUtility.UrlEncode(item.Value));

                i++;
            }

            // Create a byte array of the data we want to send
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

            // Set the content length in the request headers
            request.ContentLength = byteData.Length;
            request.Accept = "application/json";
            request.Headers.Add("X-AYLIEN-TextAPI-Application-ID",
                APPLICATION_ID);
            request.Headers.Add("X-AYLIEN-TextAPI-Application-Key",
                APPLICATION_KEY);

            // Write data
            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }

            // Get response
            using (HttpWebResponse response = request.GetResponse()
                as HttpWebResponse)
            {
                // Get the response stream
                StreamReader reader =
                    new StreamReader(response.GetResponseStream());

                // Serialize to JSON dynamic object
                var serializer = new JavaScriptSerializer();
                return serializer.Deserialize(reader.ReadToEnd(),
                    typeof(object));
            }
        }
    }

    // http://stackoverflow.com/a/3806407/1455811
    public sealed class DynamicJsonConverter : JavaScriptConverter
    {
        public override object Deserialize(IDictionary<string, object>
            dictionary,
            Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");

            return type == typeof(object) ?
                new DynamicJsonObject(dictionary) : null;
        }

        public override IDictionary<string, object>
            Serialize(object obj, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override IEnumerable<Type> SupportedTypes
        {
            get { return new ReadOnlyCollection<Type>
                (new List<Type>(new[] { typeof(object) })); }
        }

        #region Nested type: DynamicJsonObject

        private sealed class DynamicJsonObject : DynamicObject
        {
            private readonly IDictionary<string, object> _dictionary;

            public DynamicJsonObject(IDictionary<string, object> dictionary)
            {
                if (dictionary == null)
                    throw new ArgumentNullException("dictionary");
                _dictionary = dictionary;
            }

            public override string ToString()
            {
                var sb = new StringBuilder("{");
                ToString(sb);
                return sb.ToString();
            }

            private void ToString(StringBuilder sb)
            {
                var firstInDictionary = true;
                foreach (var pair in _dictionary)
                {
                    if (!firstInDictionary)
                        sb.Append(",");
                    firstInDictionary = false;
                    var value = pair.Value;
                    var name = pair.Key;
                    if (value is string)
                    {
                        sb.AppendFormat("{0}:\"{1}\"", name, value);
                    }
                    else if (value is IDictionary<string, object>)
                    {
                        new DynamicJsonObject((IDictionary<string, object>)
                            value).ToString(sb);
                    }
                    else if (value is ArrayList)
                    {
                        sb.Append(name + ":[");
                        var firstInArray = true;
                        foreach (var arrayValue in (ArrayList)value)
                        {
                            if (!firstInArray)
                                sb.Append(",");
                            firstInArray = false;
                            if (arrayValue is IDictionary<string, object>)
                                new DynamicJsonObject(
                                    (IDictionary<string, object>)
                                    arrayValue).ToString(sb);
                            else if (arrayValue is string)
                                sb.AppendFormat("\"{0}\"", arrayValue);
                            else
                                sb.AppendFormat("{0}", arrayValue);

                        }
                        sb.Append("]");
                    }
                    else
                    {
                        sb.AppendFormat("{0}:{1}", name, value);
                    }
                }
                sb.Append("}");
            }

            public override bool TryGetMember(GetMemberBinder binder,
                out object result)
            {
                if (!_dictionary.TryGetValue(binder.Name, out result))
                {
                    // return null to avoid exception.
                    // caller can check for null this way...
                    result = null;
                    return true;
                }

                result = WrapResultObject(result);
                return true;
            }

            public override bool TryGetIndex(GetIndexBinder binder,
                object[] indexes, out object result)
            {
                if (indexes.Length == 1 && indexes[0] != null)
                {
                    if (!_dictionary.TryGetValue(indexes[0].ToString(),
                        out result))
                    {
                        // return null to avoid exception.
                        // caller can check for null this way...
                        result = null;
                        return true;
                    }

                    result = WrapResultObject(result);
                    return true;
                }

                return base.TryGetIndex(binder, indexes, out result);
            }

            private static object WrapResultObject(object result)
            {
                var dictionary = result as IDictionary<string, object>;
                if (dictionary != null)
                    return new DynamicJsonObject(dictionary);

                var arrayList = result as ArrayList;
                if (arrayList != null && arrayList.Count > 0)
                {
                    return arrayList[0] is IDictionary<string, object>
                        ? new List<object>(
                            arrayList.Cast<IDictionary<string, object>>()
                            .Select(x => new DynamicJsonObject(x)))
                        : new List<object>(arrayList.Cast<object>());
                }

                return result;
            }
        }

        #endregion
    }
}

Developer Sandbox:

The Sandbox is a dedicated development and testing environment, where you can test the API, utilise sample apps and start building your own intelligent apps.

Note: You will need an AYLIEN account to use the Sandbox. You can sign up here.

Documentation

Navigate to our documentation page for a detailed description of each of the functions and guides on how to invoke them.

Functions/Features:

You can see any of the features in action in our fully functional demo. Copy and paste a piece of text, URL or a tweet on our demo page and see all of the features in action.

Language Support

The following table shows the support status for different languages in all endpoints:

EndpointEnglishGermanFrenchItalianSpanishPortuguese
Article Extraction
Summarization
Classification
Unsupervised Classification
Sentiment Analysis
Entity Extraction
Concept Extraction
Microformat Extraction
Hashtag Suggestion
Language Detection

† Experimental support

All endpoints with support for more than one language accept an ISO 639-1 language code as language request parameter. It's also possible to have the API automatically detect the language of the input by passing language=auto.