JSON REST API

API Overview

We provide a simple to use JSON API built on the REST principle. Our API uses the HTTP features like verbs, authentification and status codes. Request and response bodies are JSON encoded.

Requests

All requests must go via HTTPS, the base URL is

https://api.uclassify.com/v1/
Each request need to include the Content-Type and Authorization HTTP header
Content-Type: application/json
Authorization:Token YOUR_API_KEY_HERE

Use either your read or write key (Login and see 'Api keys').

Requests in the examples below are illustrated by using the curl, by replacing the YOUR_API_KEY_HERE you can test the API from command line. If you get SSL certificate errors, you can ignore certificate verification with the -k flag or preferably install a cert bundle.

Read Calls

Read calls do not modify classifiers, they are read-only. There are 3 different endpoints for read calls, classify, keywords and getInformation. Set the authorization header to your read API key in the request. You can make read calls to classifier owned by yourself or any published classifier.

Each successful read response (HTTP status code 2xx) returns a JSON body, if the call was not successful an error response is returned.

Classify

The call classify sends one or more texts to a classifier and returns an array with one classification per text. The username is the owner of the classifier (e.g. the Sentiment classifier is owned by uClassify).

Endpoint
POST https://api.uclassify.com/v1/{username}/{classifierName}/classify
Request body
{"texts":["text 1 to process","text 2 to process"]}

Select classifier language

Multilingual classifiers will show a list of available languages above the description. E.g. see the Sentiment classifier.

Set the language in the url to one of the following language codes, 'fr' (French), 'es' (Spanish) or 'sv' (Swedish). This will assume your texts are in the given language and use the corresponding version of the classifier.

Endpoint for alternative language
POST https://api.uclassify.com/v1/{username}/{classifierName}/{language}/classify

Here is an example classifying a Spanish text on sentiment.

Response

The classify response consists of an array of classifications. Each classification corresponds to a text in the request. Classifications are listed in the same order as the texts, meaning the classification for the first text is the first element in the array.

Name Type Description
textCoveragedoubleThe propotion of the classified text that was found in the training data. 1 means that every word was used, 0 that no words were used. Useful to determine the relevance of the classification.
classificationArrayArray of classes and respective probability.
classNameRestrictedStringThe name of the class.
pdoubleThe probability that the text belongs to this class [0-1].
This example shows how you send one text to the public 'Sentiment' classifier, which returns a classification.
curl -X POST -H "Authorization:Token YOUR_READ_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"I am so happy today\"]}" https://api.uclassify.com/v1/uClassify/Sentiment/classify
Response
[
  {
    "textCoverage": 1.0,
    "classification": [
      {
        "className": "negative",
        "p": 0.133089
      },
      {
        "className": "positive",
        "p": 0.866911
      }
    ]
  }
]

Keywords

The call keywords sends one or more texts to a classifier. For each text it returns an array with relevant keywords.

Endpoint
POST https://api.uclassify.com/v1/{username}/{classifierName}/keywords
Request body
{"texts":["text 1 to process","text 2 to process"]}

Response

The keywords request returns an array with lists of keywords, one list per text.

Name Type Description
classNameRestrictedStringThe name of the class.
pdoubleThe probability (weight) that the text belongs to this class.
keywordRestrictedStringThe keyword.
This example shows how you can extract keywords from the sentiment classifier.
curl -X POST -H "Authorization:Token YOUR_READ_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"happy good fine bad stinks worse\"]}" https://api.uclassify.com/v1/uClassify/Sentiment/keywords
Response
[
  [
    {
      "className": "positive",
      "p": 0.698998,
      "keyword": "happy"
    },
    {
      "className": "negative",
      "p": 0.736395,
      "keyword": "bad"
    },
    {
      "className": "negative",
      "p": 0.8317,
      "keyword": "worse"
    },
    {
      "className": "negative",
      "p": 0.914256,
      "keyword": "stinks"
    }
  ]
]

Get classifier information

The call getInformation returns information about a classifier. It lists the classes and on how many features they have been trained.

Endpoint
GET https://api.uclassify.com/v1/{username}/{classifierName}

Response

The getInformation response contains information about a classifier. The response consists of an array with one object per class.

Name Type Description
classNameRestrictedStringThe name of the class.
totalCountintTotal number of words the class is trained on.
uniqueFeaturesintThe number of unique words the class is trained on.
Request to get information about the public 'Sentiment' classifier.
curl -X GET -H "Authorization:Token YOUR_READ_API_KEY_HERE" -H "Content-Type: application/json"  https://api.uclassify.com/v1/uClassify/Sentiment
Response
[
  {
    "className": "negative",
    "uniqueFeatures": 6832265,
    "totalCount": 208068140
  },
  {
    "className": "positive",
    "uniqueFeatures": 6607607,
    "totalCount": 180593163
  }
]

Write Calls

Requests to create, remove, addClass, removeClass, train and untrain classifiers. Set the authorization header to your write api key in the request to any write call. You can only write to classifiers owned by yourself.

Successful write requests (HTTP status code 2xx) have an empty (void) response body. If something goes wrong an error response is returned.

Create classifier

The call create creates a classifier for the account associated with the write API key.

Endpoint
POST https://api.uclassify.com/v1/me/
Request body
{"classifierName":"NameOfTheNewClassifier"}
Creates a classifier named 'MyTopics'
curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"classifierName\":\"MyTopics\"}" https://api.uclassify.com/v1/me/
If successful (HTTP status code 2xx) the response will not contain any JSON content (void).

Remove classifier

The call remove removes the specified classifier for the account associated with the write API key.

Endpoint
DELETE https://api.uclassify.com/v1/me/MyTopics
Removes the classifier named 'MyTopics'
curl -X DELETE -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json"  https://api.uclassify.com/v1/me/MyTopics
If successful (HTTP status code 2xx) the response will not contain any JSON content (void).

Add class

The call addClass adds a class to a classifier.

Endpoint
POST https://api.uclassify.com/v1/me/{classifierName}/addClass
Request body
{"className":"NameOfTheNewClass"}
Adds a class named 'Computers' to the classifier 'MyTopics'
curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"className\":\"Computers\"}" https://api.uclassify.com/v1/me/MyTopics/addClass
If successful (HTTP status code 2xx) the response will not contain any JSON content (void).

Remove class

The call removeClass removes a class from a classifier.

Endpoint
DELETE https://api.uclassify.com/v1/me/MyTopics/Computers
Removes the class named 'Computers' from the classifier 'MyTopics'
curl -X DELETE -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json"  https://api.uclassify.com/v1/me/MyTopics/Computers
If successful (HTTP status code 2xx) the response will not contain any JSON content (void).

Train classifier

The call train trains a class in a classifier on one or more texts.

Endpoint
POST https://api.uclassify.com/v1/me/{classifierName}/{className}/train
RequestBody
{"texts":["text 1 to process","text 2 to process"]}
Trains the class called 'Computers' of the classifier 'MyTopics'
curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"The motherboard was filled with good RAM and CPUs\"]}" https://api.uclassify.com/v1/me/MyTopics/Computers/train
If successful (HTTP status code 2xx) the response will not contain any JSON content (void).

Untrain classifier

The call train untrains a class in a classifier on one or more texts. The common usage for this call is to correct misstakes, if you train a classifier on a text and then untrain it on the same text the classifier will returned to the previous state. For example if a spam message incorrectly is trained as a legitimate - use this call to fix the misstake by untraining the spam message from the legitimate class and then training it (train call) on the spam class.

Endpoint
POST https://api.uclassify.com/v1/me/{classifierName}/{className}/untrain
RequestBody
{"texts":["text 1 to process","text 2 to process"]}
Untrains the class called 'Comptuers' of the classifier 'MyTopics'
curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"Bouldering is the best type of climing\"]}" https://api.uclassify.com/v1/me/MyTopics/Computers/untrain
If successful (HTTP status code 2xx) the response will not contain any JSON content (void).

Error Responses

If the request was unsuccessful (HTTP status code other than 2xx) an JSON encoded error response body is returned.

Name Type Description
statusCodeint400=BAD_REQUEST, 413=REQUEST_ENTITY_TOO_LARGE, 500=INTERNAL_SERVER_ERROR, 530=SERVICE_UNAVAILABLE
messagestringThe error message.
Trying to create a classifier 'MyTopics' but a classifier with that same name already exists
{
  "statusCode": 400,
  "message": "The classifier 'MyTopics' is already created."
}

Examples

The following are examples of how you can use the API to programmatically create classifiers. Remember that all of this is also possible via our gui!

Twitter sentiment

This shows how to send one text in one request.

curl -X POST -H "Authorization:Token YOUR_READ_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"Today is a good day\"]}" https://api.uclassify.com/v1/uClassify/Sentiment/classify
Response body
[
  {
    "textCoverage": 1.0,
    "classification": [
      {
        "className": "negative",
        "p": 0.226168
      },
      {
        "className": "positive",
        "p": 0.773832
      }
    ]
  }
]

This shows how to batch multiple texts in one request. In this case it's 5 tweets that are classified for sentiment.

curl -X POST -H "Authorization:Token YOUR_READ_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"I am so happy today\",\"Tomorrow will be a horrible day\",\"I hate mornings\",\"Machine learning is fun\",\"Others prove theorems. Geoff Hinton proves axioms.\"]}" https://api.uclassify.com/v1/uClassify/Sentiment/classify
Response body
[
  {
    "textCoverage": 1.0,
    "classification": [
      {
        "className": "negative",
        "p": 0.133089
      },
      {
        "className": "positive",
        "p": 0.866911
      }
    ]
  },
  {
    "textCoverage": 1.0,
    "classification": [
      {
        "className": "negative",
        "p": 0.964776
      },
      {
        "className": "positive",
        "p": 0.0352237
      }
    ]
  },
  {
    "textCoverage": 1.0,
    "classification": [
      {
        "className": "negative",
        "p": 0.954094
      },
      {
        "className": "positive",
        "p": 0.0459057
      }
    ]
  },
  {
    "textCoverage": 1.0,
    "classification": [
      {
        "className": "negative",
        "p": 0.149686
      },
      {
        "className": "positive",
        "p": 0.850314
      }
    ]
  },
  {
    "textCoverage": 1.0,
    "classification": [
      {
        "className": "negative",
        "p": 0.352569
      },
      {
        "className": "positive",
        "p": 0.647431
      }
    ]
  }
]

Sentiment classifier in Spanish

This shows how to use the Spanish version of the sentiment classifier, only difference is the use of the language in the url (='es').

curl -X POST -H "Authorization:Token YOUR_READ_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"estoy tan feliz hoy\"]}" https://api.uclassify.com/v1/uClassify/Sentiment/es/classify
Response body
[
  {
    "textCoverage": 1.0,
    "classification": [
      {
        "className": "negative",
        "p": 0.133089
      },
      {
        "className": "positive",
        "p": 0.866911
      }
    ]
  }
]

Creating a Fantasy Language Classifier step-by-step

Let's say that you want to create a classifier that finds detects what Fantasy Language a text is written in. The first steps you take are

  1. Register and get a free uClassify account
  2. Under the tab 'Api Keys' obtain your read and write keys

Now you have an account and can use your write API key to programatically create classifiers. The following examples shows how to create a classifier that distinguishes text between the classes Klingon, Sindarin and Huttese. This is done in one request, however it's possible to split it into one for each call, or any number. And of course it's possible (and necessary) to continue training the classifier with more texts for each fantasy language.

  1. Create the new classifier, 'FantasyLanguage'
    curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"classifierName\":\"FantasyLanguage\"}" https://api.uclassify.com/v1/me/

The request simply creates a classifier named 'MySentiment' using the write call create. The id attribute is set to an arbitrary identifier for that call. Each request sends back an xml response, informing you if the request was successful or not. You can now log in to your account and be able to find a classifier called 'ManOrWoman' under the 'Classifiers' tab. The next thing to do is to add the possible classes. In our sentiment classifier there are two classes, 'Positive' and 'Negative'.

  1. Add 'Klingon' class to 'FantasyLanguage'
    curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"className\":\"Klingon\"}" https://api.uclassify.com/v1/me/FantasyLanguage/addClass
  1. Add 'Sindarin' class to 'FantasyLanguage'
    curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"className\":\"Sindarin\"}" https://api.uclassify.com/v1/me/FantasyLanguage/addClass
  1. Add 'Huttese' class to 'FantasyLanguage'
    curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"className\":\"Huttese\"}" https://api.uclassify.com/v1/me/FantasyLanguage/addClass

Before we can start using the classifier we need to train it. To do this we need collect training data for each class. In this case it would be a bunch of positive texts and negative. For simplicity of this example we train it on one short message per class.

  1. Train the 'Klingon' class in 'FantasyLanguage'
    curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"JIlajneS. ghIj qet jaghmeyjaj\",\"'e' pa' jaj law' mo' jaj puS\",\"'ej Doq, SoDtaH, ghoStaH SIQal\"]}" https://api.uclassify.com/v1/me/FantasyLanguage/Klingon/train
  1. Train the 'Sindarin' class in 'FantasyLanguage'
    curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"Ingon i athrad dammen beriathar aen\",\"Hon mabathon. Rochon ellint im\",\"Lasto Carahdras, sedho, hodo\"]}" https://api.uclassify.com/v1/me/FantasyLanguage/Sindarin/train
  1. Train the 'Hutttese' class in 'FantasyLanguage'
    curl -X POST -H "Authorization:Token YOUR_WRITE_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"Kaa bazza kundee hodrudda\",\"Spasteelya bookie ookie\",\"Me dwana no bata\"]}" https://api.uclassify.com/v1/me/FantasyLanguage/Huttese/train
  1. Send a request with a text to find out in what fantasy language a text is written
    curl -X POST -H "Authorization:Token YOUR_READ_API_KEY_HERE" -H "Content-Type: application/json" --data "{\"texts\":[\"Iw bIQtqDaq bIlengjaj 'ej pa'\",\"Padol raid, athan hendad aen hon\"]}" https://api.uclassify.com/v1/YOUR_USERNAME_HERE/FantasyLanguage/classify
    Response
    [
      {
        "textCoverage": 0.222222,
        "classification": [
          {
            "className": "Huttese",
            "p": 0.00300907
          },
          {
            "className": "Klingon",
            "p": 0.994839
          },
          {
            "className": "Sindarin",
            "p": 0.00215189
          }
        ]
      },
      {
        "textCoverage": 0.181818,
        "classification": [
          {
            "className": "Huttese",
            "p": 0.00295934
          },
          {
            "className": "Klingon",
            "p": 0.00180259
          },
          {
            "className": "Sindarin",
            "p": 0.995238
          }
        ]
      }
    ]

Code examples

Here are some snippets to show how to programmatically make a requests from different languages. The code is intended to demostrate simple requests. For example json serialize and deserialization is not demonstrated.

This snippets below make a classify request, with one text "the movie is really good 5/5"

This printed response in the examples below is

[{"textCoverage":1.0,"class":[{"className":"negative","p":1.19693E-05},{"className":"positive","p":0.999988}]}]

Classify from Python

import requests
response = requests.post('https://api.uclassify.com/v1/uclassify/sentiment/classify', \
    data = "{\"texts\": [\"the movie is really good 5/5\"]}", \
    headers = {'Authorization': 'Token ' + "YOUR_READ_API_KEY_HERE"})
print(response.content)

Classify from PHP

$options = array(
    'http' => array(
		'method'  => 'POST',
		'header'  => "Authorization: Token YOUR_READ_API_KEY_HERE\r\nContent-Type: application/json\r\n",
        'content' => '{"texts": ["the movie is really good 5/5"]}',
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents('https://api.uclassify.com/v1/uclassify/sentiment/classify', false, $context);
print($result)

Classify from C#

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
namespace Example
{
  internal class CodeSample
  {
    private static void Main(string[] args)
    {
      using (var client = new HttpClient {BaseAddress = new Uri("https://api.uclassify.com/v1/")})
      {
         client.DefaultRequestHeaders.Authorization = 
           new AuthenticationHeaderValue("Token", "YOUR_READ_API_KEY_HERE");
         const string requestBody = "{\"texts\": [\"the movie is really good 5/5\"]}";
         var response = client.PostAsync("uclassify/sentiment/classify", new StringContent(requestBody)).Result;
         var content = response.Content.ReadAsStringAsync().Result;
         Console.WriteLine(content);
      }
    }
  }
}

Classify from Java

It may be a better idea to use the Apache HTTP client instead of Javas native HttpURLConnection.
package example;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
    public static void main(String[] args) throws IOException {
        byte[] requestData = "{\"texts\": [\"the movie is really good 5/5\"]}".getBytes("UTF-8");
        URL url = new URL("https://api.uclassify.com/v1/uclassify/sentiment/classify");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Content-Length", Integer.toString(requestData.length));
        conn.setRequestProperty("Authorization", "Token YOUR_READ_API_KEY_HERE");
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(requestData);
        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        for (int c = in.read(); c != -1; c = in.read()) {
            System.out.print((char) c);
        }
    }
}

Details

This section presents more in depth information about the web API.

Restrictions

Each xml request can at a maximum be 3MB. All parameters that is of the type 'RestrictedString' is restricted to a-Z, space and 0-9.

Encoding

It's important that the encoding (ASCII, UTF-8, Unicode, ANSI etc) of the training documents are the same as the documents being classified (the classifier doesn't differentiate between the encodings internally). It's possible to mix encodings (requires more training data), however, we recommend that you make sure that you train and classify on the same encoding. What encoding you use is up to you but we strongly recommend UTF-8.

API Versions

When something changes in the API a new version is added in order to maintain compatibility with current API users. This means that users explicitly need to bump their request versions to use the latest API version. The version is specified in the base url.