Chris
Chris

Reputation: 115

Gmail API returns 400 BadRequest with batch request

I'm attempting to make a batch http request (on the server with Meteor/HTTP) to gmail with the following:

batchGetMessages = (accessToken, ids) => {
  let userId = 'me';
  let url = `https://www.googleapis.com/batch`;
  let boundary = `batch_message_request`;
  let body = ``;

  _.each(ids, (id) => {
    body = `${body}
    --${boundary}
    Content-Type: application/http

    GET /gmail/v1/users/${userId}/messages/${id.id}?format=metadata&fields=id%2Cpayload
    `
  });

  body = `${body}
    --${boundary}--`

  let options = {
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': `multipart/mixed; boundary="${boundary}"`,
    },
    content: body,
  };

  let data = HTTP.post(url, options);
  console.log('data: ', data);
}

The body string winds up looking like this:

--batch_message_request
Content-Type: application/http

GET /gmail/v1/users/me/messages/15375be281102d3d?format=metadata&fields=id%2Cpayload

--batch_message_request
Content-Type: application/http

GET /gmail/v1/users/me/messages/15366f87db6bdfeb?format=metadata&fields=id%2Cpayload

--batch_message_request
Content-Type: application/http

GET /gmail/v1/users/me/messages/15365d62f152dea2?format=metadata&fields=id%2Cpayload

--batch_message_request--

My request always returns a 400 Bad Request error. I've checked similar questions but haven't been able to get this working yet:

Generating HTTP multipart body for file upload in JavaScript

Gmail REST api batch support for getting messages

Batch request - 400 bad request response

Any help or suggestions will be greatly appreciated. Thanks!

Upvotes: 0

Views: 715

Answers (1)

Chris
Chris

Reputation: 115

Well, the 400 BadRequest error seems to be caused by the newline whitespace in the string template. Removing the whitespace got everything working:

...
/* 
  the lack of whitespace is impotant in the folllowing string template:
*/
  _.each(ids, (id) => {
    body = `${body}
--${boundary}
Content-Type: application/http

GET /gmail/v1/users/${userId}/messages/${id.id}? format=metadata&fields=id%2Cpayload`
  });

  body = `${body}
--${boundary}--`;
...

There's probably a fancier way to maintain your code indentation and eliminate the whitespace, but I haven't looked for it yet.

Upvotes: 1

Related Questions