Why do I get invalid JSON payload when calling google cloud vision API from appcelerator?

Nguyen Minh picture Nguyen Minh · Mar 9, 2016 · Viewed 11.5k times · Source

I was trying to use Google vision API v1 by Alloy Appcelerator

I create a request HTTPClient and call API https://vision.googleapis.com/v1/images:annotate?key=MY_APP_KEY

But i have get response text from google :

  {
 error = {
     code = 400;
     details = (
                  {
                     "@type" = "type.googleapis.com/google.rpc.BadRequest";
                      fieldViolations = ({
                                        description = "Invalid JSON payload received. Unknown name \"request\": Cannot bind query parameter. Field 'request' could not be found in request message.";
                                        });
                  }
                );
     message = "Invalid JSON payload received. Unknown name \"request\": Cannot bind query parameter. Field 'request' could not be found in request message.";
     status = "INVALID_ARGUMENT";
  };

}

And there is my code use HTTP request by Alloy

var requests =  
{
  "requests":[
    {
      "image":{
        "content": "image_have_encodebase64",
      },
      "features":[
        {
          "type":"TEXT_DETECTION",
          "maxResults":1
        }
      ]
    }
  ]
};
var xhr = Titanium.Network.createHTTPClient();
xhr.open("POST", 'https://vision.googleapis.com/v1/images:annotate?key=MY_APP_KEY');
xhr.send(JSON.stringify(requests));

Thanks for your help

Answer

Russell Mehring picture Russell Mehring · May 16, 2017

By setting the Content-Length and Content-Type headers it should work:

xhr.setRequestHeader("Content-Length", size);
xhr.setRequestHeader("Content-Type", "application/json");

Also it should be noted that Google recommends resizing your image to 1024 x 768 -- you can resize your image with:

img = img.imageAsResized(1024,768);

After making these changes to my code I had everything working.