Invoke-MgGraphRequest: How to Execute Custom Graph API Calls in Microsoft 365
This article explains how to use the Invoke-MgGraphRequest cmdlet in Graph PowerShell to perform custom API operations. Learn how to make GET, POST, PATCH, and DELETE requests with practical examples and troubleshooting tips
The Invoke-MgGraphRequest cmdlet in Microsoft Graph PowerShell allows users to send custom requests to the Microsoft Graph API. This cmdlet is particularly useful for performing operations not directly supported by Graph PowerShell cmdlets, offering a flexible way to interact with the API.
Cmdlet Syntax
Invoke-MgGraphRequest
[-Method] <HttpMethod>
[-Uri] <String>
[-Body <Object>]
[-ContentType <String>]
[-Headers <Hashtable>]
[<CommonParameters>]
Parameters
- -Method: Specifies the HTTP method for the request (e.g., GET, POST, PUT, DELETE, PATCH).
- -Uri: The endpoint of the Microsoft Graph API that you want to interact with.
- -Body: (Optional) The payload to send with the request, typically in JSON format.
- -ContentType: (Optional) The media type of the body sent to the API (default is application/json).
- -Headers: (Optional) A hashtable containing custom headers to include in the request.
Usage Examples
GET Request
$uri = "https://graph.microsoft.com/v1.0/me"
$response = Invoke-MgGraphRequest -Method GET -Uri $uri
$response | ConvertTo-Json
POST Request
$uri = "https://graph.microsoft.com/v1.0/groups"
$body = @{
displayName = "Newest Group"
mailEnabled = $true
mailNickname = "newestgroup"
securityEnabled = $false
groupTypes = @("Unified")
} | ConvertTo-Json
$response = Invoke-MgGraphRequest -Method POST -Uri $uri -Body $body
$response | ConvertTo-Json
PATCH Request
$uri = "https://graph.microsoft.com/v1.0/groups/{groupId}"
$body = @{
displayName = "Updated Group Name"
} | ConvertTo-Json
$response = Invoke-MgGraphRequest -Method PATCH -Uri $uri -Body $body
$response | ConvertTo-Json
DELETE Request
$uri = "https://graph.microsoft.com/v1.0/groups/{groupId}"
Invoke-MgGraphRequest -Method DELETE -Uri $uri
Use Cases
- Accessing Unsupported API Endpoints:
- Scenario: Sometimes, you may need to interact with Microsoft Graph API endpoints that are not directly supported by existing cmdlets in the Graph PowerShell module.
- Implementation: Use Invoke-MgGraphRequest to make direct API calls to these endpoints, allowing you to leverage the full power of the Graph API without waiting for specific cmdlets to be available.
- Benefit: Provides flexibility and access to the latest API features, enabling you to manage and automate aspects of Microsoft 365 that are otherwise inaccessible through standard cmdlets.
- Customizing API Requests:
- Scenario: You may need to send highly customized API requests that involve specific query parameters, headers, or request bodies.
- Implementation: Use Invoke-MgGraphRequest to craft custom API requests tailored to your organization’s needs, such as filtering data with complex OData queries or manipulating resources in ways that go beyond predefined cmdlets.
- Benefit: Empowers advanced users to perform more granular control and customization, ensuring that their scripts meet unique business requirements.
- Troubleshooting and Diagnostics:
- Scenario: When a standard cmdlet doesn’t behave as expected or provides incomplete information, direct API calls can help diagnose issues by retrieving raw response data.
- Implementation: Use Invoke-MgGraphRequest to make direct API calls and analyze the full JSON response, including headers and status codes, to understand what might be going wrong.
- Benefit: Provides deeper insights and debugging capabilities, helping administrators resolve issues more efficiently.
Possible Errors and Solutions
Error Message |
Cause |
Solution |
Unauthorized (401) |
You receive an unauthorized error. |
Ensure you have correct permissions and are authenticated. Use Connect-MgGraph to authenticate with appropriate scopes. Example: Connect-MgGraph -Scopes "Group.ReadWrite.All" |
Forbidden (403) |
Access to the resource is forbidden. |
Ensure your account has the necessary permissions to perform the action. |
BadRequest (400) |
Bad request due to invalid parameters. |
Verify that the URI and the body parameters are correct and conform to the API requirements. |
NotFound (404) |
The resource could not be found. |
Ensure the resource exists and the URI is correct. |
Authentication Token Expired |
You might encounter an error if the authentication token used in your API request has expired. Access tokens have a limited lifespan and must be refreshed periodically. |
Ensure that you refresh your access token before making a new API request. Connect-MgGraph -Scopes "User.Read.All"
$response = Invoke-MgGraphRequest -Method Get -Uri "https://graph.microsoft.com/v1.0/users"
|
Error: Invalid URI or API Endpoint |
Typos or incorrect API versioning in the URI can cause the request to fail. |
Double-check the URI for accuracy, including the API version, endpoint path, and any query parameters. Verify that the endpoint is correctly supported by the Graph API documentation. |
Cmdlet Tips
- Authentication: Always authenticate using Connect-MgGraph with the appropriate scopes before making requests.
- Error Handling: Implement try-catch blocks to handle errors gracefully.
- Bypass Limitations: Use this cmdlet to access API endpoints and properties not yet available via dedicated Graph PowerShell cmdlets.
- Works with All HTTP Verbs: You can make GET, POST, PATCH, PUT, or DELETE requests—ideal for advanced or unsupported scenarios.
- Beta & v1.0 Endpoints: Switch between API versions by modifying the -Uri (e.g., /v1.0/users vs /beta/users). Always validate if your action is stable before using beta in production.
- Use With Caution: Since you're crafting raw requests, there's no built-in validation. Always test with dummy data first to avoid unwanted changes.
- JSON Handling: For POST, PATCH, and PUT requests, make sure to convert your request body to JSON using ConvertTo-Json and set -ContentType to "application/json".
- Custom Headers Support: You can easily pass custom headers like If-Match, Prefer, or custom auth headers using the -Headers parameter.
- Powerful for Scripting: You can loop over results, chain multiple requests, or integrate with logging and error-handling to build automation scripts.
- Verbose Troubleshooting: Add -Verbose to get more visibility into what request is being made—helpful when debugging.
Frequently Asked Questions
- What is Invoke-MgGraphRequest used for?
Invoke-MgGraphRequest is a Microsoft Graph PowerShell cmdlet that allows you to perform custom API requests, including operations not covered by standard cmdlets. It supports all HTTP methods such as GET, POST, PATCH, and DELETE.
- How can I perform a GET request using Invoke-MgGraphRequest?
To retrieve data using a GET request, specify the API endpoint and method: Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/users"
- How can I perform a POST request to create a new user?
You can use the -Body parameter to include JSON data for the POST request:
$Body = @{
displayName = "John Doe"
mailNickname = "johndoe"
userPrincipalName = "johndoe@domain.com"
accountEnabled = $true
passwordProfile = @{
forceChangePasswordNextSignIn = $true
password = "StrongPassword123!"
}
} | ConvertTo-Json -Depth 10
Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/users" -Body $Body
- What permissions are required for Invoke-MgGraphRequest?
The permissions required depend on the specific API operation being performed. For example:
- GET /users: Requires User.Read.All or User.ReadWrite.All.
- POST /users: Requires User.ReadWrite.All.
- Can I use Invoke-MgGraphRequest to access beta endpoints in Microsoft Graph?
Yes, you can access beta endpoints by specifying the -Uri parameter with the beta version path (e.g., https://graph.microsoft.com/beta/users). However, keep in mind that beta APIs are subject to change and not recommended for production use.
- How do I pass headers like If-Match or custom authentication headers in Invoke-MgGraphRequest?
You can pass custom headers using the -Headers parameter. Example:
$headers = @{ "If-Match" = "*" }
Invoke-MgGraphRequest -Method DELETE -Uri "https://graph.microsoft.com/v1.0/teams/{team-id}" -Headers $headers
💡 Use When a Graph Endpoint Has No Cmdlet Equivalent
Invoke-MgGraphRequest is perfect for accessing Microsoft Graph endpoints that don’t yet have a native PowerShell cmdlet.
This makes it a powerful fallback for working with new, beta, or uncommon APIs directly using REST calls.
⚠️ Pay Attention to JSON Formatting in Request Bodies
When making POST, PUT, or PATCH calls with Invoke-MgGraphRequest, the -Body must be valid JSON.
Common mistakes like using single quotes, trailing commas, or missing braces will cause 400 Bad Request or parsing errors.
Conclusion
The Invoke-MgGraphRequest cmdlet provides a powerful and flexible way to interact with the Microsoft Graph API beyond predefined cmdlets. By understanding its syntax, common usage patterns, and potential errors, administrators can leverage this cmdlet to perform advanced operations and integrate deeply with Microsoft Graph services. Always ensure proper authentication and permissions to avoid common issues.