Hey there, fellow dev! Ready to dive into the world of Microsoft Graph API using Python? You're in for a treat. We'll be using the msgraph-sdk
package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get our tools ready:
pip install msgraph-sdk
Now, let's get you authenticated:
from azure.identity import ClientSecretCredential from msgraph.core import GraphClient credential = ClientSecretCredential( tenant_id="your_tenant_id", client_id="your_client_id", client_secret="your_client_secret" ) graph_client = GraphClient(credential=credential)
You've already done this in the authentication step. Easy, right?
Let's start with a simple GET request:
response = graph_client.get('/me') print(response.json())
Need to handle pagination? No sweat:
from msgraph.core import GraphClient, PageIterator def callback(data): print(data) return True client = GraphClient(credential=credential) endpoint = '/users' page_iterator = PageIterator( client, endpoint, callback ) page_iterator.iterate()
POST, PATCH, and DELETE are just as straightforward. You've got this!
Here's a quick example for each:
# Users and groups users = graph_client.get('/users').json() # Calendar and events events = graph_client.get('/me/events').json() # OneDrive and SharePoint files = graph_client.get('/me/drive/root/children').json()
Always wrap your requests in try-except blocks:
from azure.core.exceptions import HttpResponseError try: response = graph_client.get('/me') except HttpResponseError as e: print(f"Oops! {e.message}")
Remember to respect rate limits. The SDK handles most of this for you, but it's good to keep in mind.
Want to level up? Check out batch requests and change notifications. They're game-changers for performance and real-time updates.
And there you have it! You're now equipped to harness the power of Microsoft Graph API with Python. Remember, the official docs are your best friend for diving deeper.
Keep coding, keep learning, and most importantly, have fun with it!