DEV Community

Vikram Vaswani
Vikram Vaswani

Posted on • Updated on • Originally published at docs.rev.ai

Integrate Rev AI's Sentiment Analysis API with a Node.js Application

By Vikram Vaswani, Developer Advocate

This tutorial was originally published at https://docs.rev.ai/resources/tutorials/integrate-sentiment-analysis-api-nodejs/ on Apr 19, 2022.

Introduction

Sentiment analysis attempts to identify the emotional content in a text document and qualify it as positive, negative, or neutral. It is useful in a number of different scenarios, including

  • Tracking customer support satisfaction levels from customer agent interactions or written complaints
  • Analyzing political sentiment based on reactions to public speeches
  • Understanding student engagement and attitudes in class
  • Scoring leads based on sales team member interactions with prospects
  • Understanding witness attitudes in depositions

Rev AI offers a Sentiment Analysis API that provides additional speech insights by analyzing sentiments in a given transcript. As an application developer, you can use this API to obtain qualitative information about the feelings expressed in a transcribed conversation and then build applications to act on those insights.

This tutorial explains how to integrate the Rev AI Sentiment Analysis API into your Node.js application.

Assumptions

This tutorial assumes that:

NOTE: The Sentiment Analysis API is under active development. Always refer to the API documentation for the most up-to-date information.

Step 1: Install Axios

The Sentiment Analysis API is a REST API and, as such, you will need an HTTP client to interact with it. This tutorial uses Axios, a popular Promise-based HTTP client for Node.js.

Begin by installing Axios into your application directory:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Within your application code, initialize Axios as below:

const axios = require('axios');
const token = '<REVAI_ACCESS_TOKEN>';

// create a client
const http = axios.create({
  baseURL: 'https://api.rev.ai/sentiment_analysis/v1beta/',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
});
Enter fullscreen mode Exit fullscreen mode

Here, the Axios HTTP client is initialized with the base endpoint for the Sentiment Analysis API, which is https://api.rev.ai/sentiment_analysis/v1beta/.

Every request to the API must be in JSON format and must include an Authorization header containing your API access token. The code shown above also attaches these required headers to the client.

Step 2: Submit transcript for sentiment analysis

To perform sentiment analysis on a transcript, you must begin by submitting an HTTP POST request containing the transcript content, in either plaintext or JSON, to the API endpoint at https://api.rev.ai/sentiment_analysis/v1beta/jobs.

The code listings below perform this operation using the HTTP client initialized in Step 1, for both plaintext and JSON transcripts:

const submitSentimentAnalysisJobText = async (textData) => {
  return await http.post(`jobs`,
    JSON.stringify({
      text: textData
    }))
    .then(response => response.data)
    .catch(console.error);
};

const submitSentimentAnalysisJobJson = async (jsonData) => {
  return await http.post(`jobs`,
    JSON.stringify({
      json: jsonData
    }))
    .then(response => response.data)
    .catch(console.error);
};
Enter fullscreen mode Exit fullscreen mode

If you were to inspect the return value of the functions shown above, here is an example of what you would see:

{
  id: 'Sz6Fc4g6CqDM',
  created_on: '2022-03-04T06:49:44.049Z',
  status: 'in_progress',
  type: 'sentiment_analysis'
}
Enter fullscreen mode Exit fullscreen mode

The API response contains a job identifier (id field). This job identifier will be required to check the job status and obtain the job result.

Learn more about submitting a sentiment analysis job in the API reference guide.

Step 3: Check job status

Sentiment analysis jobs usually complete within 10-20 seconds. To check the status of the job, you must submit an HTTP GET request to the API endpoint at https://api.rev.ai/sentiment_analysis/v1beta/jobs/<ID>, where <ID> is a placeholder for the job identifier.

The code listing below demonstrates this operation:

const getSentimentAnalysisJobStatus = async (jobId) => {
  return await http.get(`jobs/${jobId}`)
    .then(response => response.data)
    .catch(console.error);
};
Enter fullscreen mode Exit fullscreen mode

Here is an example of the API response to the previous request after the job has completed:

{
  id: 'Sz6Fc4g6CqDM',
  created_on: '2022-03-04T06:49:44.049Z',
  completed_on: '2022-03-04T06:49:49.472Z',
  word_count: 3,
  status: 'completed',
  type: 'sentiment_analysis'
}
Enter fullscreen mode Exit fullscreen mode

Learn more about retrieving the status of a sentiment analysis job in the API reference guide.

Step 4: Retrieve sentiment analysis report

Once the sentiment analysis job's status changes to completed, you can retrieve the results by submitting an HTTP GET request to the API endpoint at https://api.rev.ai/sentiment_analysis/v1beta/jobs/<ID>/result, where <ID> is a placeholder for the job identifier.

The code listing below demonstrates this operation:

const getSentimentAnalysisJobResult = async (jobId) => {
  return await http.get(`jobs/${jobId}/result`,
    { headers: { 'Accept': 'application/vnd.rev.sentiment.v1.0+json' } })
    .then(response => response.data)
    .catch(console.error);
};
Enter fullscreen mode Exit fullscreen mode

If the job status is completed, the return value of the above function is a JSON-encoded response containing a sentence-wise sentiment analysis report. If the job status is not completed, the function will return an error instead.

Here is an example of the sentiment analysis report returned from a completed job:

{
  messages: [
    {
      content: 'I dislike tabs in code.',
      score: -0.801,
      sentiment: 'negative',
      offset: 0,
      length: 23
    },
    ...
  ]
}
Enter fullscreen mode Exit fullscreen mode

It’s also possible to filter the result set to return only positive, negative, or neutral messages by adding a filter_for query parameter to the request.

Learn more about obtaining a sentiment analysis report in the API reference guide.

Step 5: Create and test a simple application

Using the code samples shown previously, it's possible to create a simple application that accepts a plaintext document and returns its sentiment, as shown below:

const main = async (textData) => {
  const job = await submitSentimentAnalysisJobText(textData);
  console.log(`Job submitted with id: ${job.id}`);

  await new Promise((resolve, reject) => {
    const interval = setInterval(() => {
      getSentimentAnalysisJobStatus(job.id)
        .then(r => {
          console.log(`Job status: ${r.status}`);
          if (r.status !== 'in_progress') {
            clearInterval(interval);
            resolve(r);
          }
        })
        .catch(e => {
          clearInterval(interval);
          reject(e);
        });
    }, 15000);
  });

  const jobResult = await getSentimentAnalysisJobResult(job.id);
  console.log(jobResult);
};

main("I dislike tabs in code. But I love jam on toast.");
Enter fullscreen mode Exit fullscreen mode

This example application begins by invoking the main() function with two sentences of text, representing the input to be analyzed. The main() function first submits this data to the Sentiment Analysis API using the submitSentimentAnalysisJobText() method. It then uses setInterval() to repeatedly poll the API every 15 seconds to obtain the status of the job. Once the job status is no longer in_progress, it uses the getSentimentAnalysisJobResult() method to retrieve the job result and prints it to the console.

Here is an example of the output returned by the code above:

  messages: [
    {
      content: 'I dislike tabs in code.',
      score: -0.801,
      sentiment: 'negative',
      offset: 0,
      length: 23
    },
    {
      content: 'But I love jam on toast.',
      score: 0.6,
      sentiment: 'positive',
      offset: 24,
      length: 24
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

NOTE: The code listing above polls the API repeatedly to check the status of the sentiment analysis job. This is presented only for illustrative purposes and is strongly recommended against in production scenarios. For production scenarios, use webhooks to asynchronously receive notifications once the sentiment analysis job completes.

Next steps

Learn more about the topics discussed in this tutorial by visiting the following links:

Top comments (0)