Text Analytics API (v3.1-preview.4)

The Text Analytics API is a suite of natural language processing (NLP) services built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text using NLP tasks such as sentiment analysis, named entity recognition (NER) of general and personally identifiable information domains, key phrase extraction (KPE) and language detection. It can also be used to batch NER and KPE operations asynchronously to process documents with a single request. Furthermore, this API provides an asynchronous operation for analyzing unstructured clinical and biomedical text using NER, entity linking, relation extraction and entity negation tasks. More documentation can be found in https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview

Sentiment

The API returns a detailed sentiment analysis for the input text. The analysis is done in multiple levels of granularity, start from the a document level, down to sentence and key terms (targets and assessments).

Select the testing console in the region where you created your resource:

West US West US 2 East US East US 2 West Central US South Central US West Europe North Europe Southeast Asia East Asia Australia East Brazil South Canada Central UK South Japan East Central US France Central Korea Central Japan West North Central US South Africa North UAE North Switzerland North Switzerland West Central India West US 3 Norway East Jio India West

Request URL

Request parameters

(optional)
string

(Optional) This value indicates which model will be used for scoring. If a model-version is not specified, the API should default to the latest, non-preview version.

(optional)
boolean

(Optional) if set to true, response will contain request and document level statistics.

(optional)
boolean

(Optional) if set to true, response will contain not only sentiment prediction but also opinion mining (aspect-based sentiment analysis) results.

(optional)
string

(Optional) Specifies the method used to interpret string offsets. Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information see https://aka.ms/text-analytics-offsets

Request headers

string
Media type of the body sent to the API.
string
Subscription key which provides access to this API. Found in your Cognitive Services accounts.

Request body

Collection of documents to analyze.

{
	"documents": [
		{
			"id": "1",
			"language": "en",
			"text": "Great atmosphere. Close to plenty of restaurants, hotels, and transit! Staff are friendly and helpful."
		}
	]
}
{
  "type": "object",
  "required": [
    "documents"
  ],
  "properties": {
    "documents": {
      "type": "array",
      "description": "The set of documents to process as part of this batch.",
      "items": {
        "type": "object",
        "required": [
          "id",
          "text"
        ],
        "properties": {
          "id": {
            "type": "string",
            "description": "A unique, non-empty document identifier."
          },
          "text": {
            "type": "string",
            "description": "The input text to process."
          },
          "language": {
            "type": "string",
            "description": "(Optional) This is the 2 letter ISO 639-1 representation of a language. For example, use \"en\" for English; \"es\" for Spanish etc. If not set, use \"en\" for English as default."
          }
        },
        "description": "Contains an input document to be analyzed by the service."
      }
    }
  },
  "description": "Contains a set of input documents to be analyzed by the service."
}
{
	"documents": [
		{
			"id": "1",
			"language": "en",
			"text": "Great atmosphere. Close to plenty of restaurants, hotels, and transit! Staff are friendly and helpful."
		}
	]
}
{
  "type": "object",
  "required": [
    "documents"
  ],
  "properties": {
    "documents": {
      "type": "array",
      "description": "The set of documents to process as part of this batch.",
      "items": {
        "type": "object",
        "required": [
          "id",
          "text"
        ],
        "properties": {
          "id": {
            "type": "string",
            "description": "A unique, non-empty document identifier."
          },
          "text": {
            "type": "string",
            "description": "The input text to process."
          },
          "language": {
            "type": "string",
            "description": "(Optional) This is the 2 letter ISO 639-1 representation of a language. For example, use \"en\" for English; \"es\" for Spanish etc. If not set, use \"en\" for English as default."
          }
        },
        "description": "Contains an input document to be analyzed by the service."
      }
    }
  },
  "description": "Contains a set of input documents to be analyzed by the service."
}

Response 200

A successful call results in a document sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and Neutral)

{
	"documents": [
		{
			"confidenceScores": {
				"negative": 0,
				"neutral": 0,
				"positive": 1
			},
			"id": "1",
			"sentences": [
				{
					"targets": [
						{
							"confidenceScores": {
								"negative": 0,
								"positive": 1
							},
							"length": 10,
							"offset": 6,
							"relations": [
								{
									"ref": "#/documents/0/sentences/0/assessments/0",
									"relationType": "assessment"
								}
							],
							"sentiment": "positive",
							"text": "atmosphere"
						}
					],
					"confidenceScores": {
						"negative": 0,
						"neutral": 0,
						"positive": 1
					},
					"length": 17,
					"offset": 0,
					"assessments": [
						{
							"confidenceScores": {
								"negative": 0,
								"positive": 1
							},
							"isNegated": false,
							"length": 5,
							"offset": 0,
							"sentiment": "positive",
							"text": "great"
						}
					],
					"sentiment": "positive",
					"text": "Great atmosphere."
				},
				{
					"targets": [
						{
							"confidenceScores": {
								"negative": 0.01,
								"positive": 0.99
							},
							"length": 11,
							"offset": 37,
							"relations": [
								{
									"ref": "#/documents/0/sentences/1/assessments/0",
									"relationType": "assessment"
								}
							],
							"sentiment": "positive",
							"text": "restaurants"
						},
						{
							"confidenceScores": {
								"negative": 0.01,
								"positive": 0.99
							},
							"length": 6,
							"offset": 50,
							"relations": [
								{
									"ref": "#/documents/0/sentences/1/assessments/0",
									"relationType": "assessment"
								}
							],
							"sentiment": "positive",
							"text": "hotels"
						}
					],
					"confidenceScores": {
						"negative": 0.01,
						"neutral": 0.86,
						"positive": 0.13
					},
					"length": 52,
					"offset": 18,
					"assessments": [
						{
							"confidenceScores": {
								"negative": 0.01,
								"positive": 0.99
							},
							"isNegated": false,
							"length": 15,
							"offset": 18,
							"sentiment": "positive",
							"text": "Close to plenty"
						}
					],
					"sentiment": "neutral",
					"text": "Close to plenty of restaurants, hotels, and transit!"
				}
			],
			"sentiment": "positive",
			"warnings": []
		}
	],
	"errors": [],
	"modelVersion": "2020-04-01"
}
{
	"documents": [
		{
			"confidenceScores": {
				"negative": 0,
				"neutral": 0,
				"positive": 1
			},
			"id": "1",
			"sentences": [
				{
					"targets": [
						{
							"confidenceScores": {
								"negative": 0,
								"positive": 1
							},
							"length": 10,
							"offset": 6,
							"relations": [
								{
									"ref": "#/documents/0/sentences/0/assessments/0",
									"relationType": "assessment"
								}
							],
							"sentiment": "positive",
							"text": "atmosphere"
						}
					],
					"confidenceScores": {
						"negative": 0,
						"neutral": 0,
						"positive": 1
					},
					"length": 17,
					"offset": 0,
					"assessments": [
						{
							"confidenceScores": {
								"negative": 0,
								"positive": 1
							},
							"isNegated": false,
							"length": 5,
							"offset": 0,
							"sentiment": "positive",
							"text": "great"
						}
					],
					"sentiment": "positive",
					"text": "Great atmosphere."
				},
				{
					"targets": [
						{
							"confidenceScores": {
								"negative": 0.01,
								"positive": 0.99
							},
							"length": 11,
							"offset": 37,
							"relations": [
								{
									"ref": "#/documents/0/sentences/1/assessments/0",
									"relationType": "assessment"
								}
							],
							"sentiment": "positive",
							"text": "restaurants"
						},
						{
							"confidenceScores": {
								"negative": 0.01,
								"positive": 0.99
							},
							"length": 6,
							"offset": 50,
							"relations": [
								{
									"ref": "#/documents/0/sentences/1/assessments/0",
									"relationType": "assessment"
								}
							],
							"sentiment": "positive",
							"text": "hotels"
						}
					],
					"confidenceScores": {
						"negative": 0.01,
						"neutral": 0.86,
						"positive": 0.13
					},
					"length": 52,
					"offset": 18,
					"assessments": [
						{
							"confidenceScores": {
								"negative": 0.01,
								"positive": 0.99
							},
							"isNegated": false,
							"length": 15,
							"offset": 18,
							"sentiment": "positive",
							"text": "Close to plenty"
						}
					],
					"sentiment": "neutral",
					"text": "Close to plenty of restaurants, hotels, and transit!"
				}
			],
			"sentiment": "positive",
			"warnings": []
		}
	],
	"errors": [],
	"modelVersion": "2020-04-01"
}

Response 400

Bad Request.

{
	"error": {
		"code": "InvalidRequest",
		"message": "Invalid Request.",
		"innererror": {
			"code": "MissingInputRecords",
			"message": "Missing input records."
		}
	}
}
{
	"error": {
		"code": "InvalidRequest",
		"message": "Invalid Request.",
		"innererror": {
			"code": "MissingInputRecords",
			"message": "Missing input records."
		}
	}
}

Response 500

Internal error response

{
	"error": {
		"code": "InternalServerError",
		"message": "Processing failed unexpectedly. Please try again later."
	}
}
{
	"error": {
		"code": "InternalServerError",
		"message": "Processing failed unexpectedly. Please try again later."
	}
}

Code samples

@ECHO OFF

curl -v -X POST "https://canadacentral.api.cognitive.microsoft.com/text/analytics/v3.1-preview.4/sentiment?model-version={string}&showStats={boolean}&opinionMining={boolean}&stringIndexType=TextElements_v8"
-H "Content-Type: application/json"
-H "Ocp-Apim-Subscription-Key: {subscription key}"

--data-ascii "{body}" 
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
        static void Main()
        {
            MakeRequest();
            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }
        
        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");

            // Request parameters
            queryString["model-version"] = "{string}";
            queryString["showStats"] = "{boolean}";
            queryString["opinionMining"] = "{boolean}";
            queryString["stringIndexType"] = "TextElements_v8";
            var uri = "https://canadacentral.api.cognitive.microsoft.com/text/analytics/v3.1-preview.4/sentiment?" + queryString;

            HttpResponseMessage response;

            // Request body
            byte[] byteData = Encoding.UTF8.GetBytes("{body}");

            using (var content = new ByteArrayContent(byteData))
            {
               content.Headers.ContentType = new MediaTypeHeaderValue("< your content type, i.e. application/json >");
               response = await client.PostAsync(uri, content);
            }

        }
    }
}	
// // This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JavaSample 
{
    public static void main(String[] args) 
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://canadacentral.api.cognitive.microsoft.com/text/analytics/v3.1-preview.4/sentiment");

            builder.setParameter("model-version", "{string}");
            builder.setParameter("showStats", "{boolean}");
            builder.setParameter("opinionMining", "{boolean}");
            builder.setParameter("stringIndexType", "TextElements_v8");

            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Ocp-Apim-Subscription-Key", "{subscription key}");


            // Request body
            StringEntity reqEntity = new StringEntity("{body}");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) 
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    $(function() {
        var params = {
            // Request parameters
            "model-version": "{string}",
            "showStats": "{boolean}",
            "opinionMining": "{boolean}",
            "stringIndexType": "TextElements_v8",
        };
      
        $.ajax({
            url: "https://canadacentral.api.cognitive.microsoft.com/text/analytics/v3.1-preview.4/sentiment?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{subscription key}");
            },
            type: "POST",
            // Request body
            data: "{body}",
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
    NSString* path = @"https://canadacentral.api.cognitive.microsoft.com/text/analytics/v3.1-preview.4/sentiment";
    NSArray* array = @[
                         // Request parameters
                         @"entities=true",
                         @"model-version={string}",
                         @"showStats={boolean}",
                         @"opinionMining={boolean}",
                         @"stringIndexType=TextElements_v8",
                      ];
    
    NSString* string = [array componentsJoinedByString:@"&"];
    path = [path stringByAppendingFormat:@"?%@", string];

    NSLog(@"%@", path);

    NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    [_request setHTTPMethod:@"POST"];
    // Request headers
    [_request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [_request setValue:@"{subscription key}" forHTTPHeaderField:@"Ocp-Apim-Subscription-Key"];
    // Request body
    [_request setHTTPBody:[@"{body}" dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];

    if (nil != error)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSError* error = nil;
        NSMutableDictionary* json = nil;
        NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", dataString);
        
        if (nil != _connectionData)
        {
            json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
        }
        
        if (error || !json)
        {
            NSLog(@"Could not parse loaded json with error:%@", error);
        }
        
        NSLog(@"%@", json);
        _connectionData = nil;
    }
    
    [pool drain];

    return 0;
}
<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';

$request = new Http_Request2('https://canadacentral.api.cognitive.microsoft.com/text/analytics/v3.1-preview.4/sentiment');
$url = $request->getUrl();

$headers = array(
    // Request headers
    'Content-Type' => 'application/json',
    'Ocp-Apim-Subscription-Key' => '{subscription key}',
);

$request->setHeader($headers);

$parameters = array(
    // Request parameters
    'model-version' => '{string}',
    'showStats' => '{boolean}',
    'opinionMining' => '{boolean}',
    'stringIndexType' => 'TextElements_v8',
);

$url->setQueryVariables($parameters);

$request->setMethod(HTTP_Request2::METHOD_POST);

// Request body
$request->setBody("{body}");

try
{
    $response = $request->send();
    echo $response->getBody();
}
catch (HttpException $ex)
{
    echo $ex;
}

?>
########### Python 2.7 #############
import httplib, urllib, base64

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '{subscription key}',
}

params = urllib.urlencode({
    # Request parameters
    'model-version': '{string}',
    'showStats': '{boolean}',
    'opinionMining': '{boolean}',
    'stringIndexType': 'TextElements_v8',
})

try:
    conn = httplib.HTTPSConnection('canadacentral.api.cognitive.microsoft.com')
    conn.request("POST", "/text/analytics/v3.1-preview.4/sentiment?%s" % params, "{body}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################

########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '{subscription key}',
}

params = urllib.parse.urlencode({
    # Request parameters
    'model-version': '{string}',
    'showStats': '{boolean}',
    'opinionMining': '{boolean}',
    'stringIndexType': 'TextElements_v8',
})

try:
    conn = http.client.HTTPSConnection('canadacentral.api.cognitive.microsoft.com')
    conn.request("POST", "/text/analytics/v3.1-preview.4/sentiment?%s" % params, "{body}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################
require 'net/http'

uri = URI('https://canadacentral.api.cognitive.microsoft.com/text/analytics/v3.1-preview.4/sentiment')
uri.query = URI.encode_www_form({
    # Request parameters
    'model-version' => '{string}',
    'showStats' => '{boolean}',
    'opinionMining' => '{boolean}',
    'stringIndexType' => 'TextElements_v8'
})

request = Net::HTTP::Post.new(uri.request_uri)
# Request headers
request['Content-Type'] = 'application/json'
# Request headers
request['Ocp-Apim-Subscription-Key'] = '{subscription key}'
# Request body
request.body = "{body}"

response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request(request)
end

puts response.body