The purpose of this blog post is to help you to get started with Microsoft Graph API. The post shows how you can use Graph Explorer to take your first steps in learning how to use Microsoft Graph and make API calls.
Table of Contents
Introduction to Microsoft Graph API
Microsoft Graph is a RESTful API that serves as the gateway to the Microsoft 365 cloud.
MS Graph establishes a relationship between the resources (users, device, etc.) of the different M365 cloud services forming a graph-like structure and enables you to interact with the different resources using a single unified endpoint (https://microsoft.graph.com) – all by making simple API calls (REST queries) that help you to
- automate workflow(s),
- perform bulk action(s), and/or
- integrate with other service(s)
in a way that is not possible otherwise via the standard GUI portals that each of the M365 services provide.
For beginners, you can consider Microsoft Graph as just another way to access and interact with the M365 cloud resources. The only difference is that this is not GUI-based but involves queries (HTTP calls) instead.
The real advantage of Microsoft Graph can be seen when you are working with the GUI portal and to complete some particular workflow, you require to switch multiple portals. With MS Graph API, you can complete the workflow by building a script which makes and handles the API query calls programmatically, by just using one single endpoint – Microsoft Graph.
On a technical note,
MS Graph API enables you to use API queries programmatically leveraging any programming/scripting tool/platform that can make HTTP calls and interpret JSON data, and thereby serves as the foundation for inter or intra service-to-service automation (or even workflow automation for a particular resource) that are happening in the M365 cloud space. It supports OData protocol v4.0 and uses the same Microsoft identity stack (MSAL auth library) thereby using Open ID Connect for authentication and OAuth 2.0 for access tokens.
In fact, every action that we, as IT Admins, perform on the GUI-based portals, like creating and managing users, groups, policies, etc. actually gets actioned via Graph API calls that are made behind-the-scenes.
You can easily see the Graph API calls being made for an action performed on the web portal by doing a quick browser tracing [F12].
This is also the easiest and quickest way to understand and discover the Graph API, to contruct the resource URI that you want to make an API call to, by performing an action on the portal (frontend) and viewing the corresponding Graph API call being made in the backend.
Explore MS Graph with Graph Explorer
If you want to learn Microsoft Graph as a beginner, I highly suggest trying the Graph Explorer tool to run your first few Graph API queries to understand how it works and get comfortable with it.
Get to know Graph Explorer
You can access Graph Explorer easily just by typing aka.ms/ge in the URL bar of your browser.
The below screen snip shows you the Graph Explorer portal.
- Use the Sign-in to Graph Explorer button to sign-in and start using Graph Explorer.
- Choose the HTTP method for the operation – GET, POST, PUT, PATCH, DELETE.
- Choose the Graph endpoint version – beta or v1.0
- This is where you actually write your Graph API query
- Click this button to trigger the API query.
- This area lets you construct your
- Request Body (JSON payload to be supplied for the query action )
- Request Header
- Modify permissions (in preview) to change/add permissions required
- Access token lets you view your current access token
- This area shows you the Result for the query you run.
- This area shows you Sample queries to help you get started with MS Graph API, and also shows the History of queries that you ran.
Now that you have a know-how of the tool, sign-in with your account.
Authenticating and assigning Permission to Graph Explorer
Only signing-in to the tool does not suffices that you would be able to run queries straightaway.
This is because each resource you try to access using Graph API query requires permission(s) that may or may not require admin consent to be granted before the application (Graph Explorer in this case) can use it.
Always use the Microsoft Graph beta and v1 reference documentation for the resource to identify the permissions that you require to run the query.
If you run a query in Graph Explorer without having the permissions consented for that is required to access the resource in your query, you would end up getting an error like this.
Microsoft Graph supports Delegated user-level permission and Application-level permission, however, Graph Explorer can only work with Delegated permission.
Authentication and Authorization for Microsoft Graph will be covered in details in the next post of this series. Stay tuned!
Once you have the permission identified from the documentation,
- Click the small cog icon that is displayed beside your account and from the flyout menu that appears,
- Click on Select permissions
A new flyout pane appears from the right side of the screen listing all the permissions. You can use the search bar or browse through the list to get to the permissions you require and select those.
Once you have selected all the permissions that are required for the resource in context, you click on the Consent button.
Note that some permissions (majority of them!) require Admin Consent. The Status column shows if Admin has already consented for the use of that permission for this app or not. Learn more about consent and permissions experience.
Once you click on Consent button, the sign-in window will appear again. Since you are already signed-in, click on your account and you will be prompted to provide consent to the requested permissions. Click on Accept.
However, there is a catch here.
Depending on the User Settings configuration of Enterprise Applications for the tenant, especially for the particular setting as highlighted in the below snap
If your user account
- is a normal user account, i.e. without any Admin roles assigned, or
- has any other Admin role (RBAC) assigned, except Global Administrator or Cloud Application Administrator/Application Administrator,
you will land up in either of the screens as shown below.
When the particular setting is set to
- No -> You get the prompt marked as #1
In this case, you have to reach out to someone having either the Global Admin or Application Admin/Cloud Application Admin role assigned so that they can grant consent to the application and assign it to you, for you to be able to use it.
- Yes -> you get the prompt marked as #2
In this case, your request for Admin consent goes to the Admin consent reviewers as selected and once they have reviewed your request and provided consent, you will get a notification via email post which you would be able to use it.
Understanding the structure of MS Graph API – How to build query URI to make API call
Every MS Graph API call/query must follow a standard pattern as shown below
{HTTP method} https://graph.microsoft.com/{version}/{resource}?{query-parameters}
- The HTTP method for the operation must be defined. [GET, POST, PUT, PATCH, DELETE]
- Version of the Graph API to use must be specified. [v1 or beta]
- Mention of the Resource (entity and its properties) that the query will access.
- Optionally, use of parameters for filtering. (if required)
A simple example would be to build a query to fetch a particular user
HTTP Method: GET Query Format: https://graph.microsoft.com/beta/users/{user_GUID_or_UPN}
Note that MS Graph API supports building API calls (queries) to include some OData query parameters which you can use for filtering purposes. This is useful in scenarios where you only need to work with a particular property of an entity.
Consider an example where you know the user UPN and would only want to fetch details like Country, Department, etc. You can do that as shown below
HTTP Method: GET Query Format: https://graph.microsoft.com/beta/users/{user_GUID_or_UPN}?select={entity_parameters}
Run your first Graph API query in Graph Explorer
As a user, you can confirm if you have the required permissions to run a query that targets a particular resource by checking the Modify permissions (Preview) tab as shown below.
Referring to the MS Graph documentation for the resource, if you find that required permission(s) is/are missing from the current list of permissions that is already granted, you would need to add the required permissions as already shown above.
Considering that your current list of permissions suffices, you can go ahead and run your first graph API query using Graph Explorer.
Run a GET query
HTTP method GET is used to fetch data from the M365 cloud using Graph API.
Build your query as per the structure explained above and referring the MS Graph documentation. If the query succeeds, you will get an HTTP 200 OK response along with the Result (JSON).
Run a POST query
HTTP method POST is used to create a new entity for the resource type specified in the URI in the M365 cloud using Graph API. The data/values for parameters of the entity need to be provided as JSON content in the query body.
Example, lets consider an example of creating a user.
HTTP Method: POST Query Format: https://graph.microsoft.com/beta/users/
For constructing the HTTP body, you have to read the documentation for the resource type. Example, to create a resource type user, I only need to provide the required values (minimum parameters) that is required to create an entity of the specified resource type (user).
HTTP Body: { "accountEnabled": true, "displayName": "MDM Tech Space", "mailNickname": "MDMTechSpace", "userPrincipalName": "mdmtechspace@intunewithjoy.in", "passwordProfile" : { "forceChangePasswordNextSignIn": true, "password": "India@365" } }
If successful (HTTP return code 201), the HTTP Response to the above API call returns the created user object as the Result.
Run a PATCH query
HTTP method PATCH is used to update the parameter values of an existing entity/object of the specified resource type in the M365 cloud using Graph API.
Let’s take the same user object that we created above and update some property value of the object
HTTP Method: PATCH Query Format: https://graph.microsoft.com/beta/users/mdmtechspace@intunewithjoy.in/
Same as in POST, for PATCH as well, we have to provide the value(s) for the property/properties to update as HTTP body (payload) to the API call.
{ "country" : "India", "department" : "MEM Intune" }
To check if the values has been updated really, you would need to use a GET call again.
Common Errors for calling API calls with HTTP method POST/PATCH
The POST/PATCH API calls to resources requires a payload (body containing the JSON data) to be passed along with the call. Check the Graph API documentation for the resource type to confirm.
If you give an emtpy payload when the resource type requires a JSON data to be provided in the HTTP call body, you get the below error.
The body must contain data in accordance with the JSON standards. Improper syntax results in below error.
Run a DELETE query
HTTP method DELETE is used to delete an entity/object of the specified resource type from the M365 cloud using Graph API.
If successful as shown above, a GET call to the same object will result in a Request_ResourceNotFound error.
Additional errors you might encounter working with Graph API
While running Graph API queries, you may encounters errors as shown below. The cause of error can be due to
- incorrect construction of URI for the API call.
- incorrect authorization. (missing permissions!)
- exceptions. (like trying to delete a user that does not exist in the tenant!)
Refer this document to check the different HTTP errors you can expect to receive against your Graph API query calls and their probable reasons.
To be contd.
Graph Explorer serves the purpose of a Developer sandbox by letting you trigger actual Graph API query and see its result, thereby making it a very capable tool for learners as well as experienced developers and IT Pros.
The only downside of Graph Explorer – It only allows you to trigger single, independent, and individual queries. It does not let you make programmatical API calls, building a chain of queries where the result of one query acts as the input parameter for the other query.
This post marks the beginning of a new series Learn Microsoft Graph API with Joy and there will be additional blog posts to follow.