Reading OData from Dynamics 365

I’m going to show you a sample PowerShell script to read the data from Dynamics 365 products. And how to create Azure Active Directory Application and use it for authentication in Dynamics 365 for Sales and Dynamics 365 for Finance and Operations.

Create Azure Application

Open Azure portal. Find Azure Active Directory, then App registrations and click on +New application registrations.

AzureApplicationNewApplicationi

Just add your Dynamics 365 entry URLs. In our case, it will be Dynamics 365 for Sales and Dynamics 365 for Finance and Operations

AzureApplicationReplyURLs

Generate a Secret Key for your Application

AzureApplicationSecurityKey

Add Application user for Dynamics 365 for Sales

In top menu, open Settings –> Security –> Users

D365SUsersSecurity

Switch to Application Users view

D365SApplicationUserUserList

Click on +New (on the top)

And again, switch to Application User view, as it shown on the picture below

D365SApplicationUserSwitch

Enter Application ID from Azure portal, enter Full Name (your or fake) and email address. User Name will be overwritten by the email address.

Click Save. Two fields, Application ID URI and Azure AD Object ID will be populated automatically.

D365SApplicationUser

Assign the user to Role (or several Roles)

D365SManageUserRoles

Add Application user for Dynamics 365 for Finance and Operations

Open System administration –> Setup –> Azure Active Directory applications and create a new record.

Enter Client Id as Application Id from Azure portal, Enter Azure application name or any other name, then select existed AX user. Make sure that your user has default Legal Entity, not DAT.

Save it.

D365FFOAzureApplication

PowerShell script to read from OData

Please find below my PowerShell script that reads the data from Dynamics 365 via OData protocol. This script has three parts.

  • Configuration
    • $tenantDomain – your Azure tenant name or tenant GUID.
    • $ApplicationClientId and $ApplicationClientSecretKey – you may take this values from your Azure Application as described above
    • $url – URL address of the instance
    • $urlPathPart – part of the URL path. For different Dynamics 365 products, you should use right URL path.
    • $DataEntity – the name of the Entity to read. I recommend using ‘LegalEntities’ for Dynamics 365 for Finance and Operations and ‘WhoAmI’ for Dynamics 365 for Sales
  • Authorization
    • Perform OAuth2 authorization request
    • Save Bearer Token
  • Getting data
    • Perform an OData request to Dynamics 365 instance

Please find the full text of PowerShell script below

$tenantDomain = 'CTSD365.space' 
$ApplicationClientId = '833c36ad-08fb-44c0-8a30-b93935c1f5f3' 
$ApplicationClientSecretKey = 'mquFn03wemJqplNbzy9iIVKHi0hq20rD+OpnXNAhqXc='

[uri]$url =  'https://test2-integration3cd392bd94c932b1aos.cloudax.dynamics.com' 
#[uri]$url = 'https://ctsd365.crm.dynamics.com'

#$urlPathPart = '/api/data/v8.2'  #for Dynamics 365 for Sales aka CRM
$urlPathPart = '/data'  #for Dynamics 365 for Finanance and Operations aka AX

$DataEntity = 'LegalEntities' #'salesorderdetails'# 'WhoAmI' #'accounts'  #'LegalEntities' #'Contacts'

 
Write-Host "Authorization..." -ForegroundColor Yellow
Add-Type -AssemblyName System.Web
[string]$absoluteURL = $url.AbsoluteUri.Remove($url.AbsoluteUri.Length-1,1)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$Body = @{
    "client_id" = $ApplicationClientId
    "client_secret" = $ApplicationClientSecretKey
    "grant_type" = 'client_credentials'
    "scope" = "$absoluteURL/.default"
}

Write-Host "   URL" $absoluteURL -ForegroundColor Yellow
Write-Host "   Body" -ForegroundColor Yellow
$Body
Write-Host "   Trying to get authorization..." -ForegroundColor Yellow

$login = $null
$login = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$tenantDomain/oauth2/v2.0/token" -Body $Body -ContentType 'application/x-www-form-urlencoded' -Verbose

$Bearer = $null
[string]$Bearer = $login.access_token
 
Write-Host "Getting data..." -ForegroundColor Yellow
 
$headers = @{
    "Accept" = "application/xml"
    "Accept-Charset" = "UTF-8"
    "Authorization" = "Bearer $Bearer"
    "Host" = "$($url.Host)"
}

#    "Prefer" = "odata.include-annotations=""OData.Community.Display.V1.FormattedValue"""
 
[System.UriBuilder] $ListRecordsURL = $url
$ListRecordsURL.Path = "$urlPathPart/$DataEntity"
$ListRecordsURL.Query = '$top=2'

Write-Host "   URL" $ListRecordsURL -ForegroundColor Yellow
Write-Host "   Headers" -ForegroundColor Yellow
$headers
Write-Host "   Trying to get data..." -ForegroundColor Yellow


$resultREST=$null
$resultREST = Invoke-RestMethod -Method Get -Uri $ListRecordsURL.Uri.AbsoluteUri `
    -Headers $headers -ContentType 'application/json; charset=utf-8' -Verbose
 
Write-Host "Results..." -ForegroundColor Yellow
$resultREST.value | ConvertTo-Json

4 thoughts on “Reading OData from Dynamics 365”

  1. Do this also works if I try to connect to a Cloud hosted Environment? I get an error that the authentication Fails.

    Like

  2. Pingback: GeekzSoltutions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.