---
title: "Manage Office 365 With The Microsoft Graph Office 365 API"
description: "Learn to fully leverage the how to use the Microsoft Office 365 API in its various forms and incarnations in this hands-on tutorial!"
canonical: "https://adamtheautomator.com/office-365-api/"
---

# Manage Office 365 With The Microsoft Graph Office 365 API

> Learn to fully leverage the how to use the Microsoft Office 365 API in its various forms and incarnations in this hands-on tutorial!

Source: https://adamtheautomator.com/office-365-api/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Manage Office 365 With The Microsoft Graph Office 365 API](https://adamtheautomator.com/wp-content/uploads/2022/08/Manage-Office-365-With-The-Microsoft-Graph-Office-365-API.jpg)

# Manage Office 365 With The Microsoft Graph Office 365 API

[![](https://secure.gravatar.com/avatar/9a14f10ff1b1ec7d790d34f5b559e4d3de2d31b172e6ef266dfd8b479174d97b?s=192&d=mm&r=g)June Castillote](https://adamtheautomator.com/author/june/)6 September 20228 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Microsoft Office 365](/tag/microsoft-office-365/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Installing Microsoft Graph PowerShell SDK](#installing-microsoft-graph-powershell-sdk)
*   [Planning Microsoft Graph Office 365 API Permissions](#planning-microsoft-graph-office-365-api-permissions)
*   [Connecting to Microsoft Graph Office 365 API](#connecting-to-microsoft-graph-office-365-api)
*   [Creating a New User](#creating-a-new-user)
*   [Assigning Licenses to a User](#assigning-licenses-to-a-user)
*   [Adding Group Membership](#adding-group-membership)
*   [Adding Team Membership](#adding-team-membership)
*   [Conclusion](#conclusion)

Managing Office 365 resources using the [Microsoft 365 admin center](https://admin.microsoft.com/) is convenient, especially if you are on standard management, like creating users, assigning licenses, etc. But if you need to build a custom solution using automation, the Office 365 API is the way to go.

But, the Office 365 API is now legacy, and Microsoft recommends the Microsoft Graph API instead. Microsoft Graph API includes the same functionalities (and more!) that you would previously find in the Office 365 API.

> _Microsoft 365 Backup For Dummies eBook addresses the data security challenges by outlining the out-of-the-box security features in Microsoft 365. [Get eBook](https://go.veeam.com/office-365-backup-for-dummies?utm_campaign=01BR-M365-GB_Global_EN_0_Custom_WP_dummies-office365&utm_source=adamtheautomator.com&utm_medium=dcm&st=pa&ccode=dcmbloggers)_

Learn how to use the Microsoft Graph Office 365 API by example in this tutorial. Specifically, you will simulate a real-life use case of provisioning a new user, assigning licenses, and group memberships.

## Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

*   A working Office 365 tenant – [Sign up for an Office 365 trial tenant](https://www.microsoft.com/en-us/microsoft-365/enterprise/office-365-e5?activetab=pivot%3aoverviewtab) if you don’t have one for testing.
*   A [Global administrator](https://docs.microsoft.com/en-us/microsoft-365/admin/add-users/about-admin-roles?view=o365-worldwide#:~:text=on%20behalf%22%20delegates-,global%20admin,-Assign%20the%20Global) role to manage every aspect of your tenant and all resources.
*   Windows PowerShell 5.1 or the [latest PowerShell 7 release](https://github.com/PowerShell/PowerShell/releases/latest) – This tutorial uses a Windows 10 computer with PowerShell 7.2.5.

## **Installing Microsoft Graph PowerShell SDK**

As a RESTful API, you can use Microsoft Graph API in many ways, such as in an HTTP web application, JavaScript, etc. But in this tutorial, you’ll use the Microsoft Graph PowerShell SDK. This SDK is a PowerShell module you can install using the [Install-Module](https://docs.microsoft.com/en-us/powershell/module/powershellget/install-module?view=powershell-7.2) command.

Open PowerShell as administrator on your computer and run either of the below commands to install Microsoft Graph PowerShell SDK (Microsoft.Graph) for AllUsers or CurrentUser.

```powershell
# Install for all users (requires local admin access)
Install-Module Microsoft.Graph -Scope AllUsers

# Install for the current user
Install-Module Microsoft.Graph -Scope CurrentUser
```

Related:[Discover How to Run PowerShell as Administrator](https://adamtheautomator.com/powershell-run-as-administrator/)

Once installed, run the below command to confirm you have successfully installed the module.

```powershell
Get-InstalledModule
```

The latest version as of this writing is 1.10.0, as shown below.

![Verifying the Microsoft Graph PowerShell SDK’s version installed](https://adamtheautomator.com/wp-content/uploads/2022/08/image-670.png)

Verifying the Microsoft Graph PowerShell SDK’s version installed

## Planning **Microsoft Graph** Office 365 API Permissions

Working with Microsoft Graph API allows you to pick specific permissions to authorize. Does your task need read-only access to the Azure Active Directory or full access to users’ calendars? You can limit your authorization flow to allow only those permissions.

You can plan the permissions around your requirements with granular control. For example, in this tutorial, your tasks will include the following with their corresponding _minimum_ permissions.

<table><tbody><tr><td><strong>Tasks</strong></td><td><strong>Delegated Permissions</strong></td><td><strong>Application Permissions</strong></td></tr><tr><td>Create user</td><td>User.ReadWrite.All</td><td>User.ReadWrite.All</td></tr><tr><td>Read and assign licenses</td><td>User.ReadWrite.All,<br>Organization.Read.All</td><td>User.ReadWrite.All,<br>Organization.Read.All</td></tr><tr><td>Add group membership</td><td>GroupMember.ReadWrite.All</td><td>GroupMember.ReadWrite.All</td></tr><tr><td>Add user to Teams</td><td>TeamMember.ReadWrite.All</td><td>TeamMember.ReadWrite.All</td></tr></tbody></table>

Notice that there are _Delegated Permissions_ and _Application Permissions_? What’s the difference? In a delegated scenario, the permissions are limited to the signed-in user’s assigned roles. In contrast, application permissions are what you explicitly assign to it.

In this tutorial, you’ll focus on the delegated authentication flow only. The users doing the administrative task must log in (authenticate) with their user accounts while only getting specific permissions (authorization).

> _Refer to the_ [_Microsoft Graph permissions reference_](https://docs.microsoft.com/en-us/graph/permissions-reference) _to see the complete list of Microsoft Graph API permissions._

## Connecting to Microsoft Graph Office 365 API

After planning the permissions you need for your specific tasks, the next step is to authenticate and authorize with Microsoft Graph Office 365 API.

As mentioned previously, you can authenticate with user delegation or application credentials. But in this tutorial, you’ll be using the delegated user flow.

Follow the below steps to connect to Microsoft Graph PowerShell:

1\. Open a PowerShell window on your computer, and run the code below to declare the API permissions in a variable called $scopes.

```powershell
# Which permissions do you need?
$scopes = 'User.ReadWrite.All','GroupMember.ReadWrite.All','TeamMember.ReadWrite.All','Organization.Read.All'
```

2\. Next, run the following command to connect to the Microsoft Graph PowerShell. This command invokes the [Connect-MgGraph](https://m365scripts.com/microsoft365/connect-mggraph-microsoft-graph/) cmdlet and specifies the permission scopes you previously declared.

```powershell
# Connect to Microsoft Graph PowerShell
Connect-MgGraph -Scopes $scopes
```

After running the command, your default browser automatically opens and asks you to log in to your Microsoft 365 account.

3\. Once logged in, you’ll see the prompt, similar to the screenshot below, asking you to confirm the permissions requested on your behalf. As you can see, the permissions coincide with the scopes you specified.

After reviewing the permissions, click Accept to continue.

![Accepting the Microsoft Graph Office 365 API permissions](https://adamtheautomator.com/wp-content/uploads/2022/08/image-671.png)

Accepting the Microsoft Graph Office 365 API permissions

After successfully signing in, you’ll see the Welcome To Microsoft Graph! message in PowerShell.

![Verifying successful sign-in to Microsoft Graph](https://adamtheautomator.com/wp-content/uploads/2022/08/image-672.png)

Verifying successful sign-in to Microsoft Graph

4\. Finally, run the below Get-MgContext to confirm your authentication context.

```powershell
Get-MgContext
```

As you can see below, the Scopes property contains the specific API permissions you requested, and your AuthType is Delegated.

![Confirming the Microsoft Graph authentication context](https://adamtheautomator.com/wp-content/uploads/2022/08/image-673.png)

Confirming the Microsoft Graph authentication context

## Creating a New User

You’ve signed in and can now start creating a new user. In this example, you’ll create a new user in Azure AD with the following details:

<table><tbody><tr><td><strong>Display Name</strong></td><td>Patrick Star</td></tr><tr><td><strong>User principal name</strong></td><td>pstar@lzex.ga</td></tr><tr><td><strong>Firstname</strong></td><td>Patrick</td></tr><tr><td><strong>Lastname</strong></td><td>Star</td></tr><tr><td><strong>Alias</strong></td><td>PStar</td></tr><tr><td><strong>Password</strong></td><td>Scribe@Datebook1@Paramedic</td></tr><tr><td><strong>Force password reset on next sign-in</strong></td><td>True</td></tr><tr><td><strong>Account enabled</strong></td><td>True</td></tr><tr><td><strong>Usage location</strong></td><td>US</td></tr></tbody></table>

To create a new user, follow these steps:

1\. Compose the new user’s properties on the same PowerShell window, as shown below. Replace the necessary information to match your environment, especially the domain part and location.

```powershell
## Define the user details.
## NOTE: These are the minimum properties.
$userSplat = @{
    AccountEnabled    = $true
    GivenName         = 'Patrick'
    Surname           = 'Star'
    DisplayName       = 'Patrick Star'
    UserPrincipalName = 'pstar@lzex.ga'
    MailNickname      = 'PStar'
    UsageLocation     = 'US'
    passwordProfile   = @{
        password                      = 'Scribe@Datebook1@Paramedic'
        forceChangePasswordNextSignIn = $true
    }
}
```

2\. Next, run the [New-MgUser](https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.users/new-mguser) cmdlet with the user properties you defined to create a new user in step one. This command will save the result into the $user variable, which you’ll use later.

```powershell
## Create the user
$user = New-MgUser @userSplat
```

3\. Lastly, run the below [Get-MgUser](https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.users/get-mguser?view=graph-powershell-1.0) cmdlet to confirm that the new user exists in Office 365.

```powershell
## Confirm the new user exists in Azure AD.
Get-MgUser -UserId $user.Id
```

![Creating a new user in Office 365](https://adamtheautomator.com/wp-content/uploads/2022/08/image-674.png)

Creating a new user in Office 365

## Assigning Licenses to a User

You’ve created a new user, but it doesn’t have any license yet. Some organizations have a default set of licenses they assign to new accounts, depending on what their subscription has.

To assign a license to a user:

1\. Run the [Get-MgSubscribedSku](https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.identity.directorymanagement/get-mgsubscribedsku?view=graph-powershell-1.0) command below to find the available licenses and their respective identifiers.

```powershell
Get-MgSubscribedSku -All | Select-Object SkuId,SkuPartNumber,CapabilityStatus
```

![Listing available Office 365 Licenses](https://adamtheautomator.com/wp-content/uploads/2022/08/image-675.png)

Listing available Office 365 Licenses

In this example, the tenant only has two subscribed products.

<table><tbody><tr><td>SKU ID</td><td>SKU Part Number</td><td>License Display Name</td></tr><tr><td>c42b9cae-ea4f-4ab7-9717-81576235ccac</td><td>DEVELOPERPACK_E5</td><td>Microsoft 365 E5 Developer (without Windows and Audio Conferencing)</td></tr><tr><td>f30db892-07e9-47e9-837c-80727f46fd3d</td><td>FLOW_FREE</td><td>Microsoft Power Automate Free</td></tr></tbody></table>

> _Refer to_ [_Product names and service plan identifiers for licensing_](https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/licensing-service-plan-reference) _for the complete list of product names and their identifiers._

2\. Next, run the following command, which doesn’t provide output but defines the licenses in an array of hashtables (one hashtable for each license SKU ID).

Defining the licenses as below suits suppose the user requires the DEVELOPERPACK\_E5 and FLOW\_FREE licenses.

```powershell
# What are the licenses to assign
$addLicenses = @(
    @{SkuId = 'c42b9cae-ea4f-4ab7-9717-81576235ccac'} # DEVELOPERPACK_E5
    @{SkuId = 'f30db892-07e9-47e9-837c-80727f46fd3d'} # FLOW_FREE
)
```

3\. After defining the licenses, run the [Set-MgUserLicense](https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.users.actions/set-mguserlicense?view=graph-powershell-1.0) cmdlet while specifying the -AddLicenses parameter with the $addLicenses variable value. The -RemoveLicenses parameter is mandatory, but you’ll provide it with an empty array since you’re not removing any licenses from the user.

```powershell
# Assign licenses to the user
Set-MgUserLicense -UserId $user.Id -AddLicenses $addLicenses -RemoveLicenses @()
```

4\. Lastly, run the Get-MgUserLicenseDetail command to confirm that the license assignment worked. This command lists the specified user’s license details.

```
Get-MgUserLicenseDetail -UserId $user.Id 
```

The result below confirms that the user now has the licenses you assigned.

![Getting the user’s license details](https://adamtheautomator.com/wp-content/uploads/2022/08/image-676.png)

Getting the user’s license details

## Adding Group Membership

New user provisioning processes often include adding standard group memberships. Groups are helpful in assigning permissions and restrictions, such as in SharePoint and OneDrive, among others.

There are four group types that Azure Active Directory supports. These groups are:

*   Microsoft 365 groups
*   Security groups
*   Mail-enabled security groups
*   Distribution groups

Out of these four, you can only manage the _Microsoft 365 groups_ and _Security groups_ using Microsoft Graph API. The other groups are read-only.

Suppose that in this organization, all new users must become members of the following groups.

<table><tbody><tr><td>Group Name</td><td>Group Type</td><td>Group Description</td></tr><tr><td><strong>InTune – Allow Print</strong></td><td>Security Group</td><td>Members can use printers in the corporate network</td></tr><tr><td><strong>Enforce Conditional Access</strong></td><td>Security Group</td><td>Members will have Azure AD Conditional Access Rules applied</td></tr></tbody></table>

To add the user as a member of these groups:

1\. First, get the Id of each group by running the [Get-MgGroup](https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.groups/get-mggroup?view=graph-powershell-1.0) commands below. The -Filter clause looks for the group whose display name matches the group name you’re searching for.

```powershell
# 'InTune - Allow Print' group
Get-MgGroup -Filter "DisplayName eq 'InTune - Allow Print'" | Format-List Id,DisplayName,Description
# 'Enforce Conditional Access' group
Get-MgGroup -Filter "DisplayName eq 'Enforce Conditional Access'" | Format-List Id,DisplayName,Description
```

Copy the **Id** value of each group from the results. In this example, the values are as follows:

*   **InTune – Allow Print** – **3b7a95ca-a100-4da5-8924-1f47b18c13c2**
    
*   **Enforce Conditional Access** – **a78ddfe9-3758-4a78-a7c2-d1e4df6cfe26**
    

![Getting the group Id values](https://adamtheautomator.com/wp-content/uploads/2022/08/image-677.png)

Getting the group Id values

2\. After you retrieve the Group IDs, run the below commands to add the user as a member of each group. The -GroupId parameter accepts the group’s ID, and the -DirectoryObjectId accepts the user’s ID or principal name.

```powershell
# Add user as a member of the 'InTune - Allow Print' security group
New-MgGroupMember -GroupId '3b7a95ca-a100-4da5-8924-1f47b18c13c2' -DirectoryObjectId $user.id
# Add user as a member of the 'Enforce Conditional Access' security group
New-MgGroupMember -GroupId 'a78ddfe9-3758-4a78-a7c2-d1e4df6cfe26' -DirectoryObjectId $user.id
```

If the group member addition is successful, you will not see any result or output on the console.

![Adding group memberships](https://adamtheautomator.com/wp-content/uploads/2022/08/image-678.png)

Adding group memberships

3\. Finally, run the [Get-MgUserMemberOf](https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.groups/get-mggroupmemberof?view=graph-powershell-1.0) command below to confirm that the user is now a member of the groups. Note that the code uses line continuation for brevity.

```powershell
Get-MgUserMemberOf -UserId $user.Id | `
    Select-Object Id, @{n = 'Group Name'; e = { $_.AdditionalProperties.displayName } }
```

The result below lists the user’s group memberships.

![Listing group memberships](https://adamtheautomator.com/wp-content/uploads/2022/08/image-679.png)

Listing group memberships

## Adding Team Membership

Adding a user to a Team is a little bit trickier. But don’t worry. Follow the step-by-step instructions below, and you should do fine.

Suppose your new user must become a member of the Finance Team. If so, you must find the Finance Team’s ID.

1\. Run the following Get-MgGroup command to find the Finance Team’s ID.

> _Note: To search for a different team name, replace the name Finance Team in the filter clause._

```powershell
Get-MgGroup -Filter `
    "resourceProvisioningOptions/Any(x:x eq 'Team') and displayName eq 'Finance Team'"
```

Copy the Team Id value for later use.

![Finding the Team ID](https://adamtheautomator.com/wp-content/uploads/2022/08/image-680.png)

Finding the Team ID

2\. Next, compose the body parameter in the following format. In this example, you don’t need to change anything in the below code. Just copy/paste the code into PowerShell and press Enter.

> _Note: To make the user an owner of the team, insert the word “owner” into the Roles array (e.g., Roles = @(“owner”)). If not, the user will become a regular member of the team._

```powershell
$bodyParams = @{
    "@odata.type"     = "#microsoft.graph.aadUserConversationMember"
    Roles             = @()
    "User@odata.bind" = "https://graph.microsoft.com/v1.0/users('" + $user.id + "')"
}
```

3\. Finally, run the below code to add the user as a Team member. Replace the -TeamId parameter value with your appropriate Team Id.

```powershell
New-MgTeamMember -TeamId '6402116c-12cf-419e-9a47-4ed170783c55' -BodyParameter $bodyParams | Format-List DisplayName,Roles,AdditionalProperties
```

![Adding the user as a Team member](https://adamtheautomator.com/wp-content/uploads/2022/08/image-681.png)

Adding the user as a Team member

> _Microsoft 365 Backup For Dummies eBook addresses the data security challenges by outlining the out-of-the-box security features in Microsoft 365. [Get eBook](https://go.veeam.com/office-365-backup-for-dummies?utm_campaign=01BR-M365-GB_Global_EN_0_Custom_WP_dummies-office365&utm_source=adamtheautomator.com&utm_medium=dcm&st=pa&ccode=dcmbloggers)_

## Conclusion

Managing Office 365 with the Microsoft Graph Office 365 API can be a steep learning curve. But the long-term benefits outweigh the effort to learn it. You can build customized solutions or scripts that could validate your skills as a toolmaker.

The sample use-case you learned in this tutorial only covered the basics. Microsoft Graph API has more functionalities than this tutorial can teach. For example, you can improve user creation by adding a step to upload a user’s photo or enabling [multifactor authentication (MFA)](https://adamtheautomator.com/office-365-mfa/) right off the bat.

Related:[Leverage Office 365 MFA to Regain Control Now \[Tutorial\]](https://adamtheautomator.com/office-365-mfa/)

There are so many possibilities, and it would only do you good to start exploring what the Microsoft Graph Office 365 API can do for you now!

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Foffice-365-api%2F&text=Manage%20Office%20365%20With%20The%20Microsoft%20Graph%20Office%20365%20API)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Foffice-365-api%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Foffice-365-api%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2022/08/How-to-Use-the-Microsoft-Office-365-External-Email-Warning.jpg)

### [How to Use the Microsoft Office 365 External Email Warning](/external-email-warning/)

Learn how to leverage and use the Microsoft Office 365 external email warning for enhanced security and protect your users!

![](https://adamtheautomator.com/wp-content/uploads/2022/08/Amazing-Data-Visualization-With-Power-BI-Python.jpg)

### [Amazing Data Visualization With Power BI Python](/power-bi-python/)

Learn how to effectively use Power BI Python data visualizations to enhance your IT systems administration in this ATA Learning tutorial!

![](https://adamtheautomator.com/wp-content/uploads/2022/08/Avoid-False-Positives-with-Office-365-Whitelist-Domain.jpg)

### [Avoid False Positives with Office 365 Whitelist Domain](/office-365-whitelist-domain/)

Spam is everyone now-a-days, but learn how you can avoid false positives with the Office 365 whitelist domain functionality!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
