Back

Reading and Writing Data Using the Microsoft Graph API

Aug 7, 20247 minute read

Hey there, fellow JavaScript devs! Ready to dive into the world of Microsoft Graph API? Let's get our hands dirty with some data syncing for user-facing integrations. Buckle up!

The Lowdown on Microsoft Graph API

Microsoft Graph API is your one-stop shop for accessing data across Microsoft 365 services. It's a powerhouse for building integrations that keep your users' data in sync. Trust me, once you get the hang of it, you'll wonder how you ever lived without it.

Authentication: Your Ticket to the Party

First things first, we need to get you through the door. Microsoft Graph API uses OAuth 2.0, so let's grab that access token:

const msal = require('@azure/msal-node'); const config = { auth: { clientId: 'YOUR_CLIENT_ID', authority: 'https://login.microsoftonline.com/YOUR_TENANT_ID' } }; const cca = new msal.ConfidentialClientApplication(config); async function getToken() { const result = await cca.acquireTokenByClientCredential({ scopes: ['https://graph.microsoft.com/.default'] }); return result.accessToken; }

Reading Data: Time to Get Nosy

Now that we're in, let's start snooping around. Here's how you can fetch a user's profile:

const axios = require('axios'); async function getUserProfile(accessToken) { const response = await axios.get('https://graph.microsoft.com/v1.0/me', { headers: { Authorization: `Bearer ${accessToken}` } }); return response.data; }

Pro tip: Don't forget about pagination when dealing with large datasets. The API's got your back with @odata.nextLink.

Writing Data: Leave Your Mark

Reading's fun, but let's shake things up a bit. Here's how you can update a user's phone number:

async function updatePhoneNumber(accessToken, phoneNumber) { await axios.patch('https://graph.microsoft.com/v1.0/me', { mobilePhone: phoneNumber }, { headers: { Authorization: `Bearer ${accessToken}` } } ); }

Delta Queries: The Secret Sauce of Efficient Syncing

Want to keep things speedy? Delta queries are your new best friend. They'll help you sync only what's changed:

async function getDeltaChanges(accessToken, deltaLink) { const url = deltaLink || 'https://graph.microsoft.com/v1.0/me/messages/delta'; const response = await axios.get(url, { headers: { Authorization: `Bearer ${accessToken}` } }); return { changes: response.data.value, deltaLink: response.data['@odata.deltaLink'] }; }

Batch Requests: Because Why Not Kill Multiple Birds with One Stone?

Batch requests are like the Swiss Army knife of API calls. Here's how to bundle multiple operations:

async function batchRequest(accessToken, requests) { const response = await axios.post('https://graph.microsoft.com/v1.0/$batch', { requests }, { headers: { Authorization: `Bearer ${accessToken}` } } ); return response.data.responses; }

Error Handling and Retries: Because Stuff Happens

The internet isn't perfect (shocker, I know). Let's add some retry logic to handle those pesky network hiccups:

async function retryableRequest(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (i === maxRetries - 1) throw error; await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i))); } } }

Webhooks: Stay in the Loop

Want real-time updates? Webhooks have got you covered. Here's a quick setup:

async function createSubscription(accessToken, resource, notificationUrl) { const response = await axios.post('https://graph.microsoft.com/v1.0/subscriptions', { changeType: 'created,updated', notificationUrl, resource, expirationDateTime: new Date(Date.now() + 3600 * 1000).toISOString() }, { headers: { Authorization: `Bearer ${accessToken}` } } ); return response.data; }

Best Practices: The Cherry on Top

  1. Mind the rate limits. Microsoft Graph API is generous, but don't push your luck.
  2. Cache smartly. Your users (and Microsoft's servers) will thank you.
  3. Keep it secure. Treat access tokens like your deepest, darkest secrets.

Wrapping Up

There you have it, folks! You're now armed with the knowledge to build some killer integrations with Microsoft Graph API. Remember, practice makes perfect, so get out there and start coding!

Need more? The Microsoft Graph documentation is a goldmine of information. Now go forth and conquer the world of data syncing!