Search code examples
javascriptgoogle-cloud-platformgoogle-authenticationgoogle-language-api

Simple authentication with Google Natural Language API using only client javascript


Is it possible to use Google's Natural Language Cloud API using just a simple API key? The authentication documents seem to indicate it is by suggesting to use it for cURL testing, yet when I try with the below code I get a 404 message on the URL.

<html>
  <head>
    <script src="https://apis.google.com/js/api.js"></script>
    <script>
      function start() {
        gapi.client.init({
          'apiKey': 'XXXXXXX'
        }).then(function() {
          return gapi.client.request({
            path: '/v1beta1/documents:analyzeSentiment',
            method: 'POST',
            body: {'document': {
                      'type': 'PLAIN_TEXT',
                      'content': 'ANALZE THIS, IS IT BAD?'
                   } 
            }  
          });
        }).then(function(resp) {
          console.log(resp.result);
        }, function(reason) {
          console.log('Error: ' + reason.result.error.message);
        });
      };
      gapi.load('client', start);
    </script>
  </head>
  <body>
    <div id="results"></div>
  </body>
</html>

Solution

  • It does work, I just had the incorrect method specified:

    <html>
      <head>
        <script src="https://apis.google.com/js/api.js"></script>
        <script>
          function start() {
            gapi.client.init({
              'apiKey': 'XXXX',
              'discoveryDocs': ['https://language.googleapis.com/$discovery/rest?version=v1beta1']
            }).then(function() {
              return gapi.client.language.documents.analyzeSentiment({
                // not sure how to put in a JSON object in here correctly
                'document': {
                          'type': 'PLAIN_TEXT',
                          'content': 'ANALZE THIS YOU MARVELLOUS PERSON'
                       }
              });
            }).then(function(resp) {
              console.log(resp.result);
            }, function(reason) {
              console.log('Error: ' + reason.result.error.message);
            });
          };
          gapi.load('client', start);
        </script>
      </head>
      <body>
        <div id="results"></div>
      </body>
    </html>