How to create batch request to gmail api in angular 7

682 Views Asked by At

The short and sweet is...What code can I use within angular 7 to make batch requests to the gmail api batch endpoint?

I have been able to successfully make a batch request with the gmail api using postman...using the raw body format but cannot seem to craft the proper post request to the gmail api batch endpoint from within my angular 7 app. I am receiving error response 400, due to invalid syntax.

In postman it is as simple as setting the token with Authorization: Bearer and Content-Type: multipart/mixed; boundary="foo_bar" then making the body a raw request with:

--foo_bar
Content-Type: application/http

GET /gmail/v1/users/me/threads/16805106cf1751bc

--foo_bar
Content-Type: application/http

GET /gmail/v1/users/me/threads/16804cfeaeb94c4a

--foo_bar--

I have tried this in angular 7:

private readonly BATCH_API_URL: string = 'https://www.googleapis.com/batch/gmail/v1';

batchTest() {
  let authToken = this.authService.getToken();
  let body = `--foo_bar
              Content-Type: application/http
              GET /gmail/v1/users/me/threads/16805106cf1751bc

              --foo_bar
              Content-Type: application/http
              GET/gmail/v1/users/me/threads/16804cfeaeb94c4a

              --foo_bar--`

  this.httpClient.post(this.BATCH_API_URL, body, {
    headers: new HttpHeaders({
      'Authorization': `Bearer ${authToken}`,
      'Content-Type': `multipart/mixed; boundary="foo_bar"`
    })
  }).subscribe(response => {
    console.log(response);
  })

}

I have also tried:

let body = String.raw`--foo_bar\r\nContent-Type: application/http\r\n\r\nGET /gmail/v1/users/me/threads/16805106cf1751bc\r\n\r\n--foo_bar--`

...and a few other long shots like converting the string to a BufferArray and passing that in as body...

I'm trying to figure out how to properly form the body of the post request to the gmail api batch endpoint so that I can make and receive batch requests...Super thankful to anybody that can help me to solve this.

1

There are 1 best solutions below

0
On
let body ='--foo_bar\n' +
   'Content-Type: application/http\n\n' + 
   'GET https://www.googleapis.com/gmail/v1/users/me/threads/16805106cf1751bc\n' + 
   '--foo_bar\n' + 
   'Content-Type: application/http\n\n' + 
   'GET https://www.googleapis.com/gmail/v1/users/me/threads/16805106cf1751bc\n' + 
   '--foo_bar--'

Had a similar problem to you. Fixed it by concatenating a group of strings for the body instead of using a multi line string (`). Which seemed to add in unwanted spaces and line breaks

Also by including the full HTTP Request within the batch body.