Search code examples
pythongoogle-apigmailgmail-apigoogle-api-python-client

How do I send a batch request to the Gmail-API in python?


I am currently writing a small python script that works with the Gmail-API. I am trying to send a batch request to the gmail server. As the native method of gmail for sending batch request got depreciated in August 2020 I have to construct one myself. It has to be of the form 'multipart/mixed'.

According to the documentation it has to look like this (https://developers.google.com/gmail/api/guides/batch): Example batch request according to the gmail api documentation

I tried to use the python request library, but it seems it does only support requests of the form 'multipart/form'. But I am not sure.

# A list with all the message-id's.
messages = tqdm(gmail.list_messages('me'))

gmailUrl = "https://gmail.googleapis.com/batch/gmail/v1"

request_header = {"Host": "www.googleapis.com", "Content-Type": "multipart/mixed", "boundary"="bound"}

request_body = ""

# I want to bundle 80 GET requests in one batch.
# I don't know how to proceed from here.
for n in range(0,80):


response = req.post(url=gmailUrl, auth=creds, headers=request_header, files=request_body)

print(response)

So my question is pretty straightforward:

How can I send a http request with python to the Gmail-API with a 'multipart/mixed'-form.

Thanks in advance!


Solution

  • You can add each request to the batch, then execute the batch. For example:

    list_response = service.users().threads().list(userId='me').execute()
    threads = list_response['threads']
    bt = service.new_batch_http_request()
    for thread in threads:
        bt.add(service.users().threads().get(userId='me', id=thread['id']))
    bt.execute()
    

    The bt object will now have fields _requests and _responses, which you can now access - this will require some string parsing (I used ast).