In order to stay connected with Office 365 in terms of mail, calendar, contacts, documents, directory, devices, and more, Microsoft has provided the Graph API.
Naturally, this is a great and easy way to perform operations against Office 365 and building your custom solution for example.
One capability provided by the APIs is the possibility to get or update your profile picture, the data that we get or post is a binary data not encoded in bade-64, the supported size are: ’48×48′, ’64×64′, ’96×96′, ‘120×120’, ‘240×240’, ‘360×360′,’432×432’, ‘504×504’, and ‘648×648’.
Let’s start firstly getting a picture, there are several ends points as you can see below:
GET /me/photo/$value GET /users/{id | userPrincipalName}/photo/$value GET /groups/{id}/photo/$value GET /me/contacts/{id}/photo/$value GET /users/{id | userPrincipalName}/contacts/{id}/photo/$value GET /me/contactfolders/{contactFolderId}/contacts/{id}/photo/$value GET /users/{id | userPrincipalName}/contactfolders/{contactFolderId}/contacts/{id}/photo/$value
In this example I’ll try to retrieve my picture with the classic URL /me/photo/$value, I experimented that with Node.js and I used request the simplified HTTP client, it’s important don’t forget to append the access token when I’m going to make the request, below the request how looks like:
request.get('https://graph.microsoft.com/v1.0/me/photo/$value', { auth: { bearer: token }, encoding: null, }, function (err, response, body) { if (err) { reject(err); } else if (body.error) { reject(body.error.message); } else { // The value of the body will be an array. resolve(body); } });
In the following snipped I’m able to encode the binary data in base-64:
var attachmentFileName = 'myPicture.jpg'; var base64 = Buffer.from(result).toString('base64'); var contentType = 'image/jpg';
I can use this value in the source attribute of an HTML img:
<img src="base64....." >
Now it’s time to see how to change my picture, for this purpose we can use two HTTP methods indiscriminately, PATCH or PUT, in the sample below I used PATCH:
request.patch('https://graph.microsoft.com/v1.0/me/photo/$value', { auth: { bearer: token }, headers: { 'Content-type': 'image/jpeg' }, body: picture }, function (err, response, body) { if (err) { reject(err); } else if (body.error) { reject(body.error.message); } else { // The value of the body will be an array. resolve(body); } });
In the body we have to append the binary data of the picture that we want to upload and the game is over.
If you have no idea how to get the access token, take a look at the Microsoft Graph Quick Start.
Reference:
De Luca, G. (2018). Displaying and updating your Office 365 profile picture with Microsoft Graph API. [online] Available at: https://delucagiuliano.com/displaying-your-office-365-profile-picture-with-microsoft-graph-api/#.WunFXIgvyUk [Accessed 2 May. 2018].