How to Use the Google Natural Language API with Apps Script
Google Natural Language API helps you make sense of unstructured data. You can pass a string, like a tweet or transcribed speech, to the Natual Language API and it will detect the entities (like person, places, products, events), the sentiment (whether customers are happy or mad at your brand), and the syntax (parts of speech).
The Cloud Natural Language API can analyze sentences in multiple languages and it has a REST API so you can easily use it with your Google Apps Script projects. For instance, the Twitter Archiver add-on saves tweets in a Google Sheet. NLP API can be used to understand the emotion or sentiments in a tweet to determine the satisfaction level of customers on social media.
To get started, go to script.google.com and create a new project. Then go to Resources - Cloud Platform Project to open Google Developers Console. Here go to the API section and enable the Natular Language API under Google Cloud Machine Learning. Next click on Credentials to create an API key for your Google Script.
function analyzeText() {
var text = 'The quick brown fox jumped over the lazy dog';
var requestUrl = ['https://language.googleapis.com/v1/documents:analyzeSentiment?key=', 'THIS_IS_THE_API_KEY'].join(
''
);
// Use documents:analyzeEntities API endpoint for analyzing entities
// Use documents:analyzeSyntax API endpoint for synctactic (linguistic) analysis
var data = {
document: {
language: 'en-us',
type: 'PLAIN_TEXT',
content: text,
},
encodingType: 'UTF8',
};
var options = {
method: 'POST',
contentType: 'application/json',
payload: JSON.stringify(data),
};
var response = UrlFetchApp.fetch(requestUrl, options);
var data = JSON.parse(response);
Logger.log(data);
}
Things to know:
- If you don’t specify document.language, then the language will be automatically detected.
- You can upload the text file to Google Cloud Storage and specify the URI without the need to send the contents of the file in the body of your request.
- Google Cloud Natural Language API requires billing to be enabled.
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory