Displaying and updating your Office 365 profile picture with Microsoft Graph API

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.

Microsoft Graph API | Giuliano DE Luca Blog
Microsoft 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:

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:

In this request, I specified “encoding: null” which is definitely required to get the binary data of the picture, but is not enough, in fact, if I want to display the picture I need to work with the base-64 format and how to do that?
In the following snipped I’m able to encode the binary data in base-64:

I can use this value in the source attribute of an HTML img:

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:

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.

You can find this sample in my Github where I developed a Node.Js Bot:
https://github.com/giuleon/O365-Bot-Oauth2