Connecting to MS Dynamics for OData tests

Created by Jeremy Burgess, Modified on Mon, 29 Jan at 11:50 AM by Jeremy Burgess

Symptoms

You want to be able to test API data connectivity with MS Dynamics.


Cause

n/a


Resolution

First, install the MSAL.PS module which ise used for authentication. This only needs to be done once on the computer.

# Check PowerShellGet version
Get-Module -Name PowerShellGet -ListAvailable | Select-Object -Property Name, Version, Path

# Update PowerShellGet if it's outdated
Install-Module -Name PowerShellGet -Repository PSGallery -Force

# Install the module
Install-Module -Name MSAL.PS -Force

The use the following script to test the API connectivity:

# Import MSAL module
Import-Module MSAL.PS
 
#PowerShell script to test connection to Dynamics 365 Purchase Orders endpoint
#Azure AD and Dynamics 365 details
$TenantId = "<guid>"
$authority = "https://login.microsoftonline.com/$tenantId"
$Resource = "https://blah.dynamics.com" # Your Dynamics 365 URL
 
# Acquire Token Interactively
$tokenRequest = Get-MsalToken -ClientId "04b07795-8ddb-461a-bbee-02f9e1bf7b46" -Authority $authority -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Scopes "$Resource/.default" -Interactive
  
#Headers with the access token
$Headers = @{
    Authorization = "Bearer $($tokenRequest.AccessToken)"
}
 
#Purchase Orders endpoint in Dynamics 365
$PurchaseOrdersEndpoint = "$Resource/api/data/v9.1/purchaseorders"
 
#Test GET request
try {
  $PurchaseOrdersResponse = Invoke-RestMethod -Uri $PurchaseOrdersEndpoint -Headers $Headers -Method Get
  Write-Output "Successfully connected to the Purchase Orders endpoint."
  Write-Output $PurchaseOrdersResponse
} catch {
  Write-Error "Failed to connect to the Purchase Orders endpoint. Error: $_"
}

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article