polymer-2.xgoogle-apis-explorer

How to Properly Authenticate Google Vision API Using Polymer


I am trying to run a test on the Google Cloud Vision API to see how it fares to the client side Shape Detection API.

I am hoping to POST JSON with a base64 encoded image and get image text and barcodes returned.

I have created a GCP project and API key per the tutorial at (https://cloud.google.com/vision/docs/before-you-begin), but am getting an 401 error when trying to make requests.

error: {code: 401,…}
code: 401
message: "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."
status: "UNAUTHENTICATED"

The request is written in Polymer 2.x as follows:

<iron-ajax id="googleApi" 
  body="[[request]]" 
  content-type="application/json" 
  handle-as="json"
  headers$='{"Authorization": "Bearer [[GOOGLE_API_KEY]]"}' 
  last-response="{{response}}" 
  loading="{{loading}}"
  method="post" 
  url="https://vision.googleapis.com/v1/images:annotate">
</iron-ajax>

...

GOOGLE_API_KEY: {
  type: String,
  value: 'AIza0101010110100101101010'
}

...

getRequest(image) {
  let encoded = image.toString('base64');
  this.request = {
    "requests": [{
      "image": {
        "content": encoded
      },
      "features": [{
        "type": "LABEL_DETECTION",
        "maxResults": 1
      }]
    }]
  };
  let request = this.$.googleApi.generateRequest();
  request.completes.then(req => {
    console.log('submission complete');
    console.log(this.response);
  })
  .catch(error => {
    console.log(error);
  })
}

How do I resolve this authentication error?

It is an account admin issue? Improperly formatted code?


Solution

  • The authorization header is not needed, so the request should be in the form of:

    <iron-ajax id="googleApi" 
      body="[[request]]" 
      content-type="application/json" 
      handle-as="json"
      last-response="{{response}}" 
      loading="{{loading}}"
      method="post" 
      url="https://vision.googleapis.com/v1/images:annotate?key=[[GOOGLE_API_KEY]]">
    </iron-ajax>