How to make Cloud Natural Language classifyText API work with AppScript

203 Views Asked by At

I dont know why this is working. This code below works for analyzeSentiment.


  function analyzeText() {
    
  var apiKey = 'myapi';

  var text = 'I really love dogs!';

  var requestUrl = ['https://language.googleapis.com/v1/documents:analyzeSentiment?key=', apiKey].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);
}

But when I try it on classifyText it's throwing me this error below. Basically I just changed the requestUrl var from https://language.googleapis.com/v1/documents:analyzeSentiment?key= to https://language.googleapis.com/v1/documents:classifyText?key=

Error code:

Exception: Request failed for https://language.googleapis.com returned code 400. Truncated server response: {
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"encodingType\": Cannot find field.",
    "status": "I... (use muteHttpExceptions option to examine full response)
analyzeText @ Code.gs:30

Please kindly let me know what's missing in the code.

Thanks

1

There are 1 best solutions below

0
Vishal K On

As @johndee31415 suggested, the documents.classifyText doesn't take the encodingType parameter in the request body. So, remove encodingType parameter and provide a long enough text to resolve it. Refer to this documents.classifyText documentation for more information.