0

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

  • [Edit] to provide official documentation link – TheMaster Jul 10 '22 at 09:54
  • 2
    According to the docs, `documents.classifyText` doesn't take the `encodingType` parameter in the request body. You can check the API explorer at the bottom of the [documentation for documents.classifyText](https://cloud.google.com/natural-language/docs/reference/rest/v1beta2/documents/classifyText). If you leave out `encodingType` and provide a long enough text, it returns with status 200. – johndee31415 Jul 10 '22 at 10:41
  • I tried it earlier but now I realized that my text string should be longer to make it work! It doesn't work on one sentence. Thanks – Kojak Eugenio Jul 10 '22 at 13:24
  • @KojakEugenio, If my answer addressed your question, consider accepting it. If not, let me know so that the answer can be improved. Accepting an answer will help the community members with their research as well :) – Vishal K Jul 15 '22 at 14:37

1 Answers1

1

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.

Vishal K
  • 1,368
  • 1
  • 7
  • 15