Batching Azure Graph API requests in Python

For advanced users of Azure Graph API, the volume of requests can be huge. And calling the API once for every single request incurs network overheads and will slow down the process if there are huge amount of data to download. Microsoft introduces combining the requests via JSON requests to help speed up the process.

To use this in python, you can use the sample code below, the access_token is the token that you gotten from authenticating :

import urllib3

url_new = f"https://graph.microsoft.com/v1.0/$batch"
headers = {
        'Content-type': 'application/json',
        'Authorization': 'Bearer ' + access_token }

response = requests.request("POST", url_new, headers=headers, data=request)

For the data, it will be the requests in JSON format like below:

request = '''{
    "requests": [
        {
            "url": "/me?$select=displayName,jobTitle,userPrincipalName",
            "method": "GET",
            "id": "1"
        },
        {
            "url": "/me/messages?$filter=importance eq 'high'&$select=from,subject,receivedDateTime,bodyPreview",
            "method": "GET",
            "id": "2"
        },
        {
            "url": "/me/events",
            "method": "GET",
            "id": "3"
        }
    ]
}'''

As you will notice that the url in the requests are relative url, that means that it will call the API based on the version specified in the batch URL. In the above example, it will be referring to the v1.0 API calls. If you need the beta version of the API, simply change the v1.0 in the url_new to beta.

The response obtained will contain a list of responses, with individual status code and their responses. You may parse them accordingly.

Leave a Comment