Introduction to MS Graph API

MSGraph_Graphic.png

In this article, I will introduce you to the MS Graph API which is a powerful way to interact with Office 365 data.

Here are the objectives of this article:

  • What is MS Graph API?
  • How it came into picture?
  • What are its features, benefits and limitations?
  • MS Graph Explorer
  • MS Graph SDK

Let’s start with MS Graph API.

 

What is MS Graph API?

The official MS documentation defines MS Graph API as:

“You can use the Microsoft Graph API to interact with the data of millions of users in the Microsoft cloud. Use Microsoft Graph to build apps for organizations and consumers that connect to a wealth of resources, relationships, and intelligence, all through a single endpoint: https://graph.microsoft.com”

In a nutshell, MS Graph API gives you a single REST API endpoint which you can call to interact with “almost anything” in Office 365.

 

How it came into picture?

Prior to MS Graph API, Microsoft had different APIs for it’s different Office 365 and cloud products. Outlook, OneDrive, OneNote, Yammer all had their different APIs to interact with them.

Consider the following steps involved while dealing with different Office 365 APIs in an application:

  • Find the URL/endpoint of the API
  • Authenticate / get access token
  • Get results from the API
  • Repeat for each service
  • Manage multiple tokens for each API

It made a developer’s life difficult if one had to connect to many different APIs in an application.

As a solution, Microsoft launched the MS Graph API which is also called “One endpoint to rule them all”.

 

Why should you learn MS Graph API?

Office 365 is undoubtedly most widely used office produce worldwide. Millions of people are using the commercial versions of Office 365 suite or one or another of its products like Outlook, OneNote, etc.

On an average, a user in any office will use 2-3 hours working on different Office suite product like Outlook, Excel, Project, etc. Millions of new emails, events, etc. are generated in Outlook and millions of files are stored on OneDrive.

If you want to access all this information stored in Office 365 or on Azure, then you need MS Graph API.

 

Advantages

  • Single well-known resource

MS Graph API is the easiest way to interact with Office 365 data. Using MS Graph API, you can get mostly everything from a single endpoint https://graph.microsoft.com.

  • Ease of development

It liberates a developer from calling different Office 365 APIs and doing multiple token management.

  • Logical navigation

The entities of Office 365 are accessible in a logical way thru MS Graph API. Look again at the picture posted at the top of this article. You will see that once you access a user, all other entities related to it – files, messages, notes, etc. – are then accessible in a logical manner.

You don’t have to remember how an entity will be accessed, it follows a logical manner of graph structure.

  • Platform flexibility

MS Graph API does not mandate you to learn a new programming language. It can work with many different languages/platforms and Microsoft has launched SDKs to work with different platforms. You can work with MS Graph API in Windows/Android/iOS platforms. You can read more on it on last section of this article “MS Graph SDK”

 

Features

  • MS Identity Stack

MS Graph API does not introduce any new authentication mechanism where users have to go to register and then remember one more user name and password.

Instead, MS Graph API uses the Microsoft identity stack (which is used by 85% of fortune 500) – means that your users can login using the same familiar Azure AD / Microsoft Office 365 login credentials in your application.

MS Graph API uses Open ID Connect for authentication and OAUTH 2.0 for access tokens.

  • Open Standards

MS Graph API is based on and it supports many open web standards making it flexible and highly interoperable. Some of these standards are: 

REST – heart of MS Graph API implementation, any device/technology able to make http call and able to interpret JSON can work with MS Graph API 

JSON – lightweight format for request and response data 

OAUTH – provides API access token management, MS Graph API supports OAUTH v2.0 

ODATA – MS Graph API supports open data protocol v4.0 which is also called “The best way to REST”. It uses URL query string operators to make simple, standard and readable expressions.

I have written some articles on using optional ODATA query parameters with MS Graph API which can be found here:

 

  • Webhooks

Using webhooks, MS Graph API can send you notification for any changes in entities for which you have subscribed to. Instead of keeping on querying MS Graph API to see if there are any changes, you can use webhooks mechanism to have notification sent to you in case of any action/event happening. For example, you can subscribe to get notified when a new message arrives. 

  • Intelligence & Insights

MS Graph API does not only do simple input and output operations on your organization’s Office 365 entities. Instead of that, MS Graph API also has intelligence inbuilt in it which can help you to find treading documents around a user, people frequently contacted, etc. It can also help you find the best meeting times in a team.

  • Custom data extensions

You can extend MS Graph API results with custom data i.e. you can add custom data to MS Graph without using any external data source. This is helpful when you want to store some custom data relevant to your application e.g. profile setting or favorite theme, etc.

There are two types of extensions: Open extensions which are flexible and allows you to store any untyped data; and Schema extensions where you can define your own complex strongly typed schema, which can be shared between your different applications.

  • Delta query

Using delta query, it become easier to track data changes in entities. Instead of getting list of all entities and comparing them one by one to identify any changes, just fire a call using delta query which will give you only the changes i.e. inserted, updated, deleted data since your last call. 

  • Batching

Using MS Graph API’s JSON Batching you can combine multiple requests in one HTTP call and optimize application performance. Instead of looping thru multiple calls in your application, you can fire all related / unrelated calls in one batch in one go.

 

Limitations

The most visible one is some of its features are still in beta, but MS Graph team keeps launching new features in live regularly.

For a list of all MS Graph API known issues, refer here.

 

MS Graph API Explorer

Graph Exp

MS Graph API Explorer is a great tool to get started with MS Graph API and learn first-hand how it works. Graph Explorer is a developer sandbox where you can fire actual Graph API call and see its result.

You can access MS Graph API Explorer here.

I have written some articles on how to use MS Graph Explorer which can be found here:

 

Microsoft Graph SDK

MS Graph team has done some great work in launching SDKs for different platforms which makes development with MS Graph API easy.

You don’t have to code everything from scratch, ready to start code is available in SDK.

The following SDKs are available:

SDKs.png

If you are a java developer, then recently Microsoft has launched Java SDK for MS Graph API in preview.

If you want to add MS Graph SDK in any of your C# application, then open Visual Studio and simply search for “Microsoft Graph” in NuGet package manager to get started:

Nuget MS Graph.PNG

That’s it for introduction to MS Graph API in this article. Wait for my next article where I will show how you can start programming in MS Graph API.

Till then following links will be useful to get started with MS Graph API:

Using optional query parameters with Microsoft Graph API – Part 2

In this article, I will continue showing how to execute the calls to Microsoft Graph API using some optional OData query parameters.

The part-1 of this article series can be found here. I suggest you read it first, as this article continues from where I stopped in part -1.

Let’s now see the remaining query parameters one by one.

(5) $select

Explanation:

When you fire an API call to MS Graph, it will return the JSON result with all the properties. You may not need all the properties of a result set always. When you want MS Graph API to return only certain properties, then use $select parameter to specify which properties you want in result set.

Please note that the no. of records in the result will not be affected with or without $select parameter, only what’s returned for each record in result will change.

 Example:

Open MS Graph Explorer here and fire following call to get list of files from OneDrive:

See the data returned in JSON response:

OneDrive

Out of all these properties, what may be most important for you if you wanted to show the user his/her files from OneDrive? Of course, the name of the file/folder.

Fire following call in MS Graph Explorer to get only file name in result:

You will see the following result:

OneDrive name only.PNG

Now MS Graph API returns only file/folder name, instead of all the details. (Of course, “etag” is included but ignore it)

You can also use more than one property separated by comma, e.g.

And you will get following result:

OneDrive name size.PNG

If you type in the property that does not exist in the result set, then it will be ignored.

e.g. fire the following call and see what happens:

Usage:

In your programming, you can use $select query parameter to:

  • Get only specific property in result set (to make efficient use of bandwidth)
  • Specify those properties not returned in default result set

 

(6) $search

Explanation:

Using $search query parameter, you can specify free text search criteria for items being returned in result set. Please note that this parameter is currently supported for only “messages” and “person” entities. Microsoft Graph team will cover more entities later.

Some programmers are confused between $search and $filter parameters, because both do similar operations. I will explain the difference briefly in the next section for $filter.

When you specify $search parameter, it tells MS Graph API to include only those entities in result which match the specified expression. Here what to match is left for the implementer, OData specification does not mandate anything. Hence when you specify search criteria with $search query parameter, the result will be dependent on what MS Graph API team has decided to implement. Mostly it works as free text search.

Example:

Let’s say you want to find out emails which has “brainstorming” mentioned somewhere.

Open MS Graph Explorer here and fire following call:

See the data returned in JSON response:

search.PNG

Graph API will match the word brainstorming in an email’s from, subject and body fields, and will show the matching messages in the result.

Let’s see another example of using $search with “people” entity.

Open MS Graph Explorer here and fire following call:

See the data returned in JSON response:

people search

MS Graph API will search for the people related to the sample account user, will search for “langer” in display name or email, and will return matching records in result.

There are many more possible calls using the $search parameter, but I will restrict to there two calls only for brevity. I encourage you to explore more by yourself.

Usage:

In your programming, you can use $search parameter to:

  • perform free text search on messages or people related to user
  • perform fuzzy searches on people

 

(7) $filter

Explanation:

With $filter parameter, you can specify the filter criteria on a result set using logical operators or string functions. There are fixed logical and string operations which can be performed on a result set using $filter function.

The following extract is taken from the OData specification website here:

The $filter system query option allows clients to filter a collection of resources that are addressed by a request URL. The expression specified with $filter is evaluated for each resource in the collection, and only items where the expression evaluates to true are included in the response.

 Let’s understand the difference between $search and $filter parameters:

$search starts with an empty result set and adds items to it based on criteria that match, while $filter takes full result set, and removes items based on criteria that don’t match.

$search operates like a free text search, while $filter works on predefined logical and string functions.

Which logical and string functions are supported with $filter?

As per current MS Graph API documentation, following functions are supported, but the support varies as per which entity you are dealing with, so always refer to latest documentation on Microsoft site:

  • equals (eq)
  • not equals (ne)
  • greater than (gt)
  • greater than or equals (ge)
  • less than (lt), less than or equals (le)
  • and (and)
  • or (or)
  • not (not)
  • startswith
  • any

Example:

Let’s see some examples of how you can use $filter parameter.

Open MS Graph Explorer here and fire following call:

See the data returned in JSON response, it returns all people associated with the sample account whose job title is not set:

filter job title

Similarly, if you want to see only those records where job title is set, then simply change the operator “eq” (for equal to) to “ne” (for not equal to)

You will see the following response which will list all users who has job title assigned:

filter job title not null

Please note here that you see only 2 properties in the response, because I also used the $select parameter in the API call. You can use “&” in an API call when you want to use more than one optional query parameter: two parameters.PNG

There are many more uses of $filter parameter possible, but I will restrict to only two examples for brevity. I suggest you read more on Microsoft Graph API documentation page here.

Usage:

Use the $filter parameter in your programming to:

  • make API calls with logical operations for checking equality, greater than, less than, etc. operations

 

(8) $skipToken

Explanation:

When a response from MS Graph API does not contain all the available records (due to user explicitly specifying to select only some top records or due to server-side paging implemented in Graph API to limit response size), then you will see the response contains a server generated value with $skipToken parameter.

This value is to be specified in the next call to MS Graph API so that it will return the next set of records. The value of $skipToken is generated by server, it can not be specified by you as a consumer.

Example:

Fire the following call to get only top 10 files stored on user’s OneDrive:

See the result, note the value in @odata.nextLink property:

skip token value

The @odata.nextLink property contains the call which should be fired to get the next set of result. For identifying what should be returned, it has a skip token generated from server-side with some logic to skip those records in current response.

Simply fire the query mentioned in the @odata.nextLink property, and you will get next set of values.

Usage:

  • In your programming, you can use $skipToken to get paginated data (implement paging).

 

Limitations/Errors

Not all query parameters are supported for all entities. Always refer to latest Microsoft documentation for what’s supported. I also suggest firing the call in MS Graph Explorer first and see if you are getting the expected result or not, before starting any programming and later having any surprise.

If you include some query parameter for a non-supported entity, then MS Graph API will throw appropriate error.

Let’s understand with an example.

Fire following call in MS Graph Explorer:

You will get error 400:

 filter 123

 

Using query parameter without ‘$’ prefix in beta version of MS Graph API

With beta version of MS Graph API, using “$” prefix before a query parameter is optional.

Fire following call in MS Graph Explorer to get top 2 recently accessed files in result:

You will see the following result:

beta top

Note that the “top” query parameter is used without any “$” prefix here and still you get only 2 records in result.

This concludes my 2-part article series on MS Graph API query parameters. I hope you enjoyed learning about how to use query parameters in the MS Graph API call.

I suggest you keep reading more about MS Graph API until my next article.

You can read some of my articles on MS Graph API here.

 

Header image courtesy: Microsoft

This article may be published by me on other websites too.

 

Using optional query parameters with Microsoft Graph API – Part 1

How to use optional OData query parameters while working with MS Graph API

In this article, I will explain how to execute the calls to Microsoft Graph API using some optional OData query parameters.

The objectives of this article are:

  • What are the optional OData query parameters?
  • List of supported OData query parameters, when to use which one
  • Execute some Graph API calls using query parameters

While Microsoft already has the documentation to cover all its technology, in this article, I will try to explain these OData query parameters with some different angles and usage scenarios. I’m sure you will enjoy reading this article and learn something new.

Background

This article shows how you can fire some calls to MS Graph API using optional query parameters with the MS Graph Explorer available here:

Office Development

In my previous articles, I explained the different components of Microsoft Graph Explorer and showed how to execute MS Graph API calls using the sample account. I suggest you read those articles too for better understanding MS Graph API Explorer.

You can read my previous articles on MS Graph API Explorer here:

What are the Optional Query Parameters?

The current version of Microsoft Graph API supports the OData version 4.0 standard. This OData standard defines how the data is exchanged between the originator and the consumer of the REST APIs.

Look at the format of an API endpoint in Microsoft Graph API:

Office Development

Here “query-parameters” is an optional set of parameters to modify the response/output of API calls. It always starts with $ sign. (Please note here that in the beta version of MS Graph API, using $ is now optional. We will see that later in the article). Query parameters start after “?” sign.

The Microsoft Graph API documentation here describes the optional query parameters as:

“You can use optional query parameters to customize the response in your Microsoft Graph app. Use query parameters to include more or fewer properties than the default response, filter the response for items that match a custom query, or provide additional parameters for a method.”

The OData standards specification on www.odata.org defines the optional query parameters as “System Query Options” which are explained in great detail here.

The ODATA standards specification explains these query parameters as:

“System Query Options are query string parameters a client may specify to control the amount and order of the data that an OData service returns for the resource identified by the URI. The names of all System Query Options are prefixed with a “$” character.

An OData service may support some or all of the System Query Options defined. If a data service does not support a System Query Option, it must reject any requests which contain the unsupported option…”

In short, using these optional query parameters in the API endpoint query string you can define the criteria applicable on the result. And these parameters are optional meaning if you don’t mention any of them in the query string, then also the API call works fine.

If you are not aware of OData standard, then I suggest you to spend some time on reading about the OData specification on the odata.org website here for better understanding of OData concepts.

List of supported query parameters in Microsoft Graph API

The following query parameters are supported in the current version of Microsoft Graph API:

  • $count
  • $expand
  • $filter
  • $orderby
  • $search
  • $select
  • $skip
  • $skipToken
  • $top

A complete list with details can be found on Microsoft Graph API documentation website here.

Let’s now see each of the above query parameters one by one in detail and fire queries in Microsoft Graph API Explorer.

I will explain them in increasing order of complexity of understanding.

(1) $top

Explanation

This parameter will fetch only certain number of data items as specified along with $top.

At times, you will not need to fetch all the items from the result set, but only first few of them. In this case, $top query parameter is used to specify how many items should be returned in the result.

Usually, $top query parameter is used with $orderby query parameter (Read more about $orderby in section 3 below).

Example

Open MS Graph Explorer here and fire following calls

Notice the amount of data being returned in results in the above calls. In real life API call execution, it will return the current user’s emails and all files on his/her OneDrive. This may not be required always, and returning these many items may not be best suited option performance-wise too.

When you want to see only some limited number of records, at that time you can use $top.

Go to MS Graph Explorer here and fire the following call:

https://graph.microsoft.com/v1.0/me/messages?$top=2 or click here, then press “Run Query”.

You will see only two result items, not the list of all messages,

Office Development
Note: I have collapsed the JSON result in above screenshot to show items fit in one screen.

Usage

In your programming, you can use $top query parameter to:

  • Show recent/latest/top items from a list of items
  • Implement paging (often used with $skip and $orderby)

(2) $count

Explanation

This parameter will fetch the total number/count of data items in the specified API endpoint along with the result.

Note that the API call will return the result “as it is” without this query parameter, but if this parameter is specified, then in addition to the result, a number indicating the result count is also returned.

You will see the result count in @odata.count property in response JSON.

Example

Open MS Graph Explorer here and fire following call to get list of emails

It will show the following result,

Office Development

Notice here as highlighted in above screenshot, MS Graph API will return to you the count of emails as the value of property @odata.count.

Fire more calls in MS Graph Explorer to understand the $count parameter as shown below

You will see MS Graph Explorer does not return any count or does not return any error, it simply returns a valid result. If the $count parameter is not applicable on the API endpoint it will ignore it.

I leave it to you now to try and explore the $count parameter with different Graph API calls.

Usage

In your programming, you can use $count query parameter to:

  • Get the no. of result items in the result, along with result item(s)

(3) $orderby

Explanation

This parameter will make the Graph API return the result in a specific sorting order. Sometimes, you will want your result from MS Graph API to be sorted in a certain order depending on the date or name or some other property of the resource being returned. Use $orderby parameter in those cases to get your result sorted in certain order.

Example

Open MS Graph Explorer here and fire following call to get all users.

You will see all the organization’s users are returned here. They are in the order of email address. You may want to have the result ordered by another property, let’s say display name.

Execute the following call

You will see the list of users is ordered by the display name of user,

Office Development
Note: In above screenshot only one result fits in the screen. Try scrolling the response view by yourself to see all the items.

The default order by is done in ascending order. If you want to order by descending order, then specify “desc” in the URL separated by a space.

Execute the following call,

You will see the list is now ordered descending by the display name:

Office Development

Usage

In your programming, you can use $orderby query parameter to:

  • Get an ordered list of result items, based on certain property
  • Get emails, events, other items in ascending or descending sort order

(4) $skip

Explanation

This query parameter tells the MS Graph API to omit the number of records as specified along with $skip from the result set. MS Graph API will follow the same sorting order it follows (if $orderby is not specified) and will omit that many number of records from the result as specified in the query string.

Example

Open MS Graph Explorer here and fire following call to get the list of contacts:

It will show the result with all contacts of sample account. Note the result’s “displayName” values for first 4 records (they start with “A”).

Now run the following query to skip first 4 records from result

You will see the result without those first 4 contacts,

Office Development

MS Graph API has omitted first 4 records from the result set.

What happens when we specify a skip count greater than no. of records in the result? Let’s find out.

Run the following query to skip 10000 records from result

We know there are no more than 10000 contacts in the sample account. This is the result you will get, it simply returns an empty set

Office Development

Usage

In your programming, you can use $skip query parameter to:

  • Omit the first few items from a list of items
  • Implement paging (often used with $top and $orderby)

We will see the rest of the parameters in next article. Until then you can go to MS Graph Explorer and try the above examples by yourself.

You can also read more of my MS Graph API articles here.

 

This article was first published by me on C# Corner Website here.

Header image courtesy: Microsoft

A First Look At The New Microsoft Graph Explorer – Part Three

Note: All my blogs on Microsoft Graph API can be found here.

In first two parts of my article series “A First Look at the New Microsoft Graph Explorer”, I explained about different components of Microsoft Graph Explorer. I suggest you to read those two parts first, before reading this third part for better understanding.

You can read the previous parts here:

I will continue the article series with part three where I will explain how to execute the calls to Microsoft Graph API.

The objectives of this article are:

  • Execute some Graph API GET calls using sample account
  • Look at Microsoft Graph API metadata
  • Calling beta API

Execute Graph API GET calls using sample account

Let’s look at some simple GET calls to Microsoft Graph API using the Graph Explorer.

Open the Microsoft Graph Explorer by clicking here.

Check the left section under “Authentication”.

Office Development

It says currently a sample account provided by Microsoft with some test data is being used. You can fire GET calls using this account right away.

If you see the API endpoint address bar you will notice,

Office Development

API endpoint for getting user’s profile is already loaded.

Simply click on “Run Query” button to execute the API call.

Office Development

You will see that the response area of the page is updated with something, like below.

Office Development

The status in the green background indicates that the call was successful with HTTP status code of 200 and executed in 869 mill seconds.

Look at the JSON data in “Response Preview” section.

It has some data of “user” which is the current user provided by Microsoft sample account. If you are logged in with your account, then you will see your data. I will cover the calls after login with your account later.

There is also something more.

Microsoft Graph API metadata

You might be wondering how to find out what data to expect in an API GET call response or what data to pass in an API call POST request. You can read the Graph API documentation or look at the sample queries on left side section, but there is also another way.

Look at the first line of the JSON response,

Office Development

You will see a URL for “@odata.context” property.

Copy the URL and paste in a new tab.

Office Development

You will see it loads an XML file. A big XML file. That’s the OData documentation of the Microsoft Graph API. Microsoft Graph API metadata in other words.

It specifies the different entities and actions along with properties and parameters.

Search for the following in the page- EntityType Name=”user”.

Office Development

You will find the user entity along with its properties and navigation properties. You will also find some more entities, more actions, functions. You can also see the Graph API metadata page directly here,

The following lines are taken from the Microsoft Graph website as it is:

“The metadata allows you to see and understand the Microsoft Graph data model, including the entity types, complex types, and Enums that make up the resources represented in the request and response packets.

You can use the metadata to understand the relationships between entities in Microsoft Graph and establish URLs that navigate between those entities.

Path URL resource names, query parameters, and action parameters and values are not case sensitive. However, values you assign, entity IDs, and other base64-encoded values are case sensitive.”

For the scope of this article, I will not go deeper inside this XML file and will leave it to you to explore more.

Back to the Graph Explorer

If you place your mouse cursor in the API address bar and press back space key and remove everything till “v1.0/” you will see the Graph Explorer will hint you possible API endpoints you can fire,

Office Development

Similarly, if you start typing “me/” then it will show you possible endpoints after “me”

Office Development

Now, type https://graph.microsoft.com/v1.0/organization in the address bar and press “Run Query” button, you will see the logged in user’s organization info,

Office Development

Please note that in Microsoft Graph API “me” and “organization” are the only two aliases in Microsoft Graph API i.e. these two are not the actual objects in Office 365.

If you want to test more GET calls, then you can see list of some GET calls in left section under “Sample Queries”.

Office Development

More GET calls featured scenarios can be found here on Microsoft Graph website,

Office Development

Calling API in preview

Now, let’s see how to call some Graph API endpoints which are still in preview i.e. in beta.

Change the API version to “Beta” in the version lookup,

Office Development

Copy and paste https://graph.microsoft.com/beta/me/insights/trending in the API endpoint address bar and press “Run Query” button,

Office Development

You will see the names of some documents are returned with their “weight”. These are the “trending” documents around the user and you need to write some code to convert the “weight” of each document to some meaningful representation to end user.

But the purpose of making this call is to make you understand how to fire a beta API call in Microsoft Graph Explorer.

Now change the API version to V1.0, keep the API endpoint URL same and fire the call,

Office Development

You will see it returns an error, because this endpoint is only in beta version and not yet in V1.0.

I hope you will play with Microsoft Graph Explorer and fire some more GET calls until I write the next article and we continue the journey of learning with the new Microsoft Graph Explorer.

Note: This article was first published by me on C# Corner website here.

Header image courtesy: Microsoft