How to Start with Microsoft Graph API


What is Microsoft Graph API?

Microsoft Graph is the gateway to data and intelligence in Microsoft 365. It provides a unified programmability model that you can use to access the tremendous amount of data in Microsoft 365, Windows, and Enterprise Mobility + Security.

 

microsoft-graph-dataconnect-connectors-enhance

 

Microsoft Graph exposes REST APIs and client libraries to access data on the following Microsoft cloud services:

  • Microsoft 365 core services: Bookings, Calendar, Delve, Excel, Microsoft 365 compliance eDiscovery, Microsoft Search, OneDrive, OneNote, Outlook/Exchange, People (Outlook contacts), Planner, SharePoint, Teams, To Do, Viva Insights
  • Enterprise Mobility + Security services: Advanced Threat Analytics, Advanced Threat Protection, Azure Active Directory, Identity Manager, and Intune
  • Windows services: activities, devices, notifications, Universal Print
  • Dynamics 365 Business Central services

 

microsoft-graph

 

Use Microsoft Graph to build experiences around the user’s unique context to help them be more productive. Imagine an app that can:

  • Looks at your next meeting and helps you prepare for it by providing profile information for attendees, including their job titles and managers, as well as information about the latest documents they’re working on, and people they’re collaborating with.
  • Scans your calendar and suggests the best times for the next team meeting.
  • Fetches the latest sales projection chart from an Excel file in your OneDrive and lets you update the forecast in real time, all from your phone.
  • Subscribes to changes in your calendar, sends you an alert when you’re spending too much time in meetings, and provides recommendations for the ones you can miss, or delegate based on how relevant the attendees are to you.
  • Helps you sort out personal and work information on your phone; for example, by categorizing pictures that should go to your personal OneDrive and business receipts that should go to your OneDrive for Business.
  • Analyzes at-scale Microsoft 365 data so that decision makers can unlock valuable insights into time allocation and collaboration patterns that improve business productivity.
  • Brings custom business data into Microsoft Graph, indexing it to make it searchable along with data from Microsoft 365 services

 

Is Microsoft Graph API free?

Microsoft Graph Data Connect consumption charges are billed monthly on a pay-as-you-go basis. The Data Connect billing unit is in a multiple of 1000s of objects, where 1 object maps to 1 individual instance of an entity in Microsoft 365. For example, 1 email == 1 object, 1 file == 1 object, 1 Teams chat message == 1 object, and so on.

 

ItemPrice
Microsoft Graph Data Connect objects€ 0.354 per 1000 objects extracted

 

There are some datasets available for free or are currently free in preview while other datasets are charged. Microsoft Graph Data Connect offers datasets across multiple different Microsoft 365 products and services.

 

There is no charge for extraction of objects from the following datasets:

  • BasicDataSet_v0.User_v0
  • BasicDataSet_v0.User_v1
  • BasicDataSet_v0.MailboxSettings
  • BasicDataSet_v0.Manager
  • BasicDataSet_v0.DirectReport
  • BasicDataSet_v0.GroupDetails
  • BasicDataSet_v0.GroupMembers
  • BasicDataSet_v0.GroupOwners

 

How to Start with Microsoft Graph API?

Microsoft Graph is a RESTful web API that enables you to access Microsoft Cloud service resources. After you register your app and get authentication tokens for a user or service, you can make requests to the Microsoft Graph API.

The Microsoft Graph API defines most of its resources, methods, and enumerations in the OData namespace, microsoft.graph, in the Microsoft Graph metadata. A small number of API sets are defined in their sub-namespaces, such as the call records API which defines resources like callRecord in microsoft.graph.callRecords.

 

How to call REST API method?

To read from or write to a resource such as a user or an email message, you construct a request that looks like the following:

 

The components of a request include:

  • {HTTP method} – The HTTP method used on the request to Microsoft Graph.
  • {version} – The version of the Microsoft Graph API your application is using.
  • {resource} – The resource in Microsoft Graph that you’re referencing.
  • {query-parameters} – Optional OData query options or REST method parameters that customize the response.

 

After you make a request, a response is returned that includes:

  • Status code – An HTTP status code that indicates success or failure. For details about HTTP error codes, see Errors.
  • Response message – The data that you requested or the result of the operation. The response message can be empty for some operations.
  • @odata.nextLink – If your request returns a lot of data, you need to page through it by using the URL returned in @odata.nextLink.

 

HTTP methods

Microsoft Graph uses the HTTP method on your request to determine what your request is doing. Depending on the resource, the API may support operations including actions, functions, or CRUD operations described below.

 

MethodDescription
GETRead data from a resource.
POSTCreate a new resource or perform an action.
PATCHUpdate a resource with new values.
PUTReplace a resource with a new one.
DELETERemove a resource.

 

  • For the CRUD methods GET and DELETE, no request body is required.
  • The POST, PATCH, and PUT methods require a request body, usually specified in JSON format, that contains additional information, such as the values for properties of the resource.

 

Version

Microsoft Graph currently supports two versions: v1.0 and beta.

  • 0 includes generally available APIs. Use the v1.0 version for all production apps.
  • beta includes APIs that are currently in preview. Because it might introduce breaking changes to the beta APIs, it is recommended that you use the beta version only to test apps that are in development; do not use beta APIs in your production apps.

 

Resource

A resource can be an entity or complex type, commonly defined with properties. Entities differ from complex types by always including an id property.

Your URL will include the resource you are interacting with in the request, such as me, user, group, drive, and site. Often, top-level resources also include relationships, which you can use to access additional resources, like me/messages or me/drive. You can also interact with resources using methods; for example, to send an email, use me/sendMail.

Each resource might require different permissions to access it. You will often need a higher level of permissions to create or update a resource than to read it.

 

Query parameters

Query parameters can be OData system query options, or other strings that a method accepts to customize its response.

You can use optional OData system query options 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.

For example, adding the following filter parameter restricts the messages returned to only those with the emailAddress property of contact@impactory.de.

GET https://graph.microsoft.com/v1.0/me/messages?filter=emailAddress eq ‘contact@impactory.de’

Aside from OData query options, some methods require parameter values specified as part of the query URL. For example, you can get a collection of events that occurred during a time period in a user’s calendar, by querying the calendarView relationship of a user, and specifying the period startDateTime and endDateTime values as query parameters:

GET https://graph.microsoft.com/v1.0/me/calendarView?startDateTime=2019-09-01T09:00:00.0000000&endDateTime=2019-09-01T17:00:00.0000000

 

Tools for interacting with Microsoft Graph

One of the tools you can use to interact with Microsoft Graph is Graph Explorer.

 

Graph Explorer

Graph Explorer is a web-based tool that you can use to build and test requests using Microsoft Graph APIs.

You can either access demo data without signing in, or you can sign in to a tenant of your own. Use the following steps to build the request:

  1. Select the HTTP method.
  2. Select the version of API that you want to use.
  3. Type the query in the request text box.
  4. Select Run Query.

The following example shows a request that returns information about users in the demo tenant:

 

Graph Explorer

 

Sample queries are provided in Graph Explorer to enable you to more quickly run common requests. To see the samples that are available, select show more samples. Select On for the set of samples that you want to see, and then after closing the selection window, you should see a list of predefined requests.

A status code and message are displayed after a request is sent and the response is shown in the Response Preview tab.

 

PowerShell Code Snippets

In order to use Microsoft Graph with PowerShell the first thing you need to do is to install Microsoft Graph PowerShell SDK.

The following prerequisites are required to use the Microsoft Graph PowerShell SDK with Windows PowerShell:

  • Upgrade to PowerShell 5.1 or later
  • Install .NET Framework 4.7.2 or later
  • Update PowerShellGet to the latest version using Install-Module PowerShellGet -Force
  • The PowerShell script execution policy must be set to remote signed or less restrictive. Use Get-ExecutionPolicy to determine the current execution policy. To set the execution policy, run: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

When you are done with prerequisites you are ready to install Microsoft Graph for PowerShell. Using the Install-Module cmdlet is the preferred installation method for the Microsoft Graph PowerShell module.

Run the following command to install the SDK in PowerShell Core or Windows PowerShell.

  • Install-Module Microsoft.Graph

After the installation is completed, you can verify the installed version with the following command.

  • Get-InstalledModule Microsoft.Graph

Now you are ready to use PowerShell for Microsoft Graph. Use the Connect-MgGraph command to sign in with the required scopes. Each API in the Microsoft Graph is protected by one or more permission scopes. The user logging in must consent to one of the required scopes for the APIs you plan to use. You’ll need to sign in with an admin account to consent to the required scopes. The command prompts you to go to a web page to sign in using a device code. Once you’ve done that, the command indicates success with a Welcome To Microsoft Graph! message. You only need to sign in once per session.

  • Connect-MgGraph -Scopes “User.Read.All”,”Group.ReadWrite.All”

E.g. with scope User.Read.All you will be able to do the following:

  • List users to find the user ID of the logged-in user
  • List joinedTeams to get the Teams the user is a member of.

Use Group.ReadWrite.All scope if you want to:

  • List channels to get the channels in a Team.
  • Send message to send a message to a Team channel.

If you don’t know what kind of permissions are needed use Find-MgGraphCommand. The Find-MgGraphCommand cmdlet can be used to discover the required permissions for another cmdlet. For example, to see all permissions that can be used to call Get-MgUser, run:

Find-MgGraphCommand -command Get-MgUser | Select -First 1 -ExpandProperty Permissions

The output will be something like this:

 

Microsoft Graph API example

 

Additionally, you can find the corresponding PowerShell code snippet in Graph Explorer after you successfully build and execute your query:

 

Microsoft Graph API Code Snippets

 

You will see which commands you can execute to get the output via PowerShell. Graph Explorer also provide you code snippets for CSharp, JavaScript, Java and Go.

 

Microsoft Graph API Examples

Where can you find basic examples of Microsoft Graph queries? The answer is on the left side in Graph Explorer. Graph queries are split by categories:

 

Microsoft Graph Examples_11

 

Expand for example Applications category to see the basic queries you can run against your applications or create a new one:

 

Graph Explorer List All Applications

 

As you can see in this example, we are using sample account and in order to get a real data you need to sing in first via the human icon on top right corner. Because we are not signed in some of the graph queries are also locked (create a new application, update application properties, delete an application and create new owner).

 

Conclusion

By using Microsoft Graph, you can take advantage of a secured, unified API to connect to data located in various Microsoft 365 services. Gaining access to this data will give users the information that they need to make timely decisions and give the company a competitive advantage. Developers can get started with Microsoft Graph quickly and access data across an organization without having to learn about how individual Microsoft 365 services work.

If you are new to Microsoft Graph and don’t know how to start in your organization don’t hesitate to contact us at Impactory GmbH. We have more than 10 years of experience in consulting services in the Microsoft 365 and SharePoint domains.

 

Additional Resources

  1. Since Microsoft Viva is getting more mature, you might want to have a read on the various Microsoft Viva Modules
  2. The Complete SharePoint Guide is your starting point if you are just beginning your journey to SharePoint.
  3. Compliance is a major concern in the cloud. How to make SharePoint Intranet GDPR Compliant is a must-read if you are going that route.

IMPACTORY

Your reliable, high-performance partner

We offer a wide range of consultancy services for the planning, introduction, and implementation of SharePoint, Microsoft 365, and hybrid applications. Benefit from our many years of experience in the industry.

Services

We will make sure that Microsoft 365 and SharePoint will run perfectly in your company.

Solutions

Innovative solutions lead to increased productivity. Our goal is to deliver impactful business solutions that can be quickly and easily implemented in your organization.