web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Small and medium business | Business Central, N...
Suggested Answer

Call the API to get a list of environments

(5) ShareShare
ReportReport
Posted on by 22
Hello. I'm a web developer working on Dynamics 365 Business Central integration.
I have registered a Microsoft Entra application and set up the Microsoft Entra application in Business Central according to this documentation

I received an access token and tested it with a request to the endpoint of the list of companies for the production environment. The request was completed successfully and I received a list of companies.
But when I use the same token to request a list of available environments, I get a 401 response code. To request a list of environments, I use the following endpoint specified in the documentation
GET https:/api.businesscentral.dynamics.com/environments/v1.1
 
I assume that the error is related to the API versions. I have the token for version v2.0. And in the endpoint of the environment list, version 1.1 is indicated.
Could you please tell me if it is possible to get a list of environments for version v2.0 through a request to the API? maybe I'm doing something wrong?
I have the same question (0)
  • Suggested answer
    Gerardo Rentería García Profile Picture
    25,234 Most Valuable Professional on at
  • Suggested answer
    YUN ZHU Profile Picture
    95,729 Super User 2025 Season 2 on at
  • Oleh Antykuz Profile Picture
    22 on at
    Thanks for the links to the documentation and URL
    It looks like I need an additional permission for the application "AdminCenter.ReadWrite.All" which was not previously delegated to the application. I'll test this after the Azure portal admin approves this permission and let you know
  • Oleh Antykuz Profile Picture
    22 on at
    Unfortunately I'm still getting a 401 response code. Even using the admin center API URL that you mentioned. I am attaching screenshots of the application settings and requests in postman. Please tell me what I missed?
     
      
     
     
     
     
     
    Thanks
     
  • AL-19062053-0 Profile Picture
    8 on at
    Hi @Oleh Antykuz I am running into the exact same issue as you – were you able to resolve this?

    EDIT: I figured it out. You need to go to the Dynamics 365 Business Central admin center, and under Microsoft Entra Apps, add the client (application) ID. You need to do this in addition to adding the application in Dynamics 365 Business Central.
     
    After doing this, the v2.24 environments route will work, but not the v1.1 route.

    EDIT 2: It looks like Sohail Ahmed shamelessly plagiarized my solution...
  • Suggested answer
    Sohail Ahmed Profile Picture
    11,148 Super User 2025 Season 2 on at

    Hope this might be helpful:

    To resolve the issue, you need to perform the following steps:

    1. Navigate to the Dynamics 365 Business Central admin center.
    2. Within the admin center, locate the Microsoft Entra Apps section.
    3. Add the client (application) ID of your application in this section.
     

    This action is required in addition to adding the application within Dynamics 365 Business Central itself.

    ✅ Mark this answer as verified if it helps you.

  • Suggested answer
    YUN ZHU Profile Picture
    95,729 Super User 2025 Season 2 on at
    Hi, updated
    Dynamics 365 Business Central: Can we get all environments within BC via AL (Not in Admin Center)
     
    Thanks.
    ZHU
  • Suggested answer
    Valery Moskalenko Profile Picture
    78 on at
    Hi,
     
    Doesn't support S2S auth. 
    You have to use Delegated User flow (Interactive Login) to make v1.1 work.
     
    V2.28 may use S2S auth.
     
    Please find PowerShell example for both V2.28 and V1.1 endpoints:
    # =============================================================================
    # Get Business Central Environments
    # =============================================================================
    # This script retrieves all BC environments for the tenant
    # 
    # Option A: Admin Center API (S2S / Client Credentials) - requires AdminCenter.ReadWrite.All
    # Option B: Environments v1.1 API (Delegated / User Context) - for Connect Apps
    #
    # Documentation: 
    #   https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api_environments
    #   https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/webservices/api-get-environments
    # =============================================================================
    $ErrorActionPreference = 'Stop' # Stop script on any error (cmdlets and native commands)
    
    # Configuration - Replace with your values
    $tenantId = "342eee93-0000-4640-86c9-b66922701891" #"YOUR_TENANT_ID"
    $clientId = "c8f13aed-0000-4514-9dd2-3377e59bd44c" #"YOUR_CLIENT_ID"
    $clientSecret = 'G.e8Q******************Zqega-t' #"YOUR_CLIENT_SECRET"
    $redirectUri = "http://localhost"  # Must be registered in Azure app
    $userEmail = ""  # Optional: Set your email to enable silent authentication (e.g., "user@company.com")
    
    # -----------------------------------------------------------------------------
    # Function: Get Access Token (S2S - Client Credentials)
    # -----------------------------------------------------------------------------
    function Get-BCAccessToken {
        param(
            [string]$TenantId,
            [string]$ClientId,
            [string]$ClientSecret,
            [string]$Scope = "https://api.businesscentral.dynamics.com/.default"
        )
        
        $tokenUrl = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
        
        $body = @{
            grant_type    = "client_credentials"
            client_id     = $ClientId
            client_secret = $ClientSecret
            scope         = $Scope
        }
        
        $response = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"
        return $response.access_token
    }
    
    # -----------------------------------------------------------------------------
    # Function: Get Delegated Access Token (Interactive Login)
    # -----------------------------------------------------------------------------
    function Get-BCDelegatedAccessToken {
        param(
            [string]$TenantId,
            [string]$ClientId,
            [string]$ClientSecret,
            [string]$RedirectUri,
            [string]$LoginHint = ""  # Optional: pre-fill username to skip account picker
        )
        
        $scope = "https://api.businesscentral.dynamics.com/.default" # OR "https://api.businesscentral.dynamics.com/.default offline_access"
        $authUrl = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/authorize"
        $tokenUrl = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
        
        $authParams = @(
            "client_id=$ClientId"
            "response_type=code"
            "redirect_uri=$([System.Uri]::EscapeDataString($RedirectUri))"
            "scope=$([System.Uri]::EscapeDataString($scope))"
            "response_mode=query"
            "prompt=select_account"  # Use existing session, skip consent if already granted
            #"prompt=none" # Silent auth. $userEmail must be filled in. Must use login_hint to avoid account picker
        )
        
        # Add login_hint if provided to skip account picker
        if ($LoginHint) {
            $authParams += "login_hint=$([System.Uri]::EscapeDataString($LoginHint))"
        }
        
        $authRequestUrl = "$authUrl`?$($authParams -join '&')"
        
        # Open browser for user login
        Write-Host "Browser will open the following URL for authentication:" -ForegroundColor Gray
        Write-Host $authRequestUrl -ForegroundColor Cyan
        Write-Host "Opening browser for authentication..." -ForegroundColor Yellow
        Write-Host "After login, you will be redirected to: $RedirectUri" -ForegroundColor Gray
        Write-Host "Copy the FULL URL from the browser address bar and paste it below." -ForegroundColor Gray
        #Start-Process $authRequestUrl
        
        # Get the authorization code from user
        Write-Host ""
        $redirectResponse = Read-Host "Paste the full redirect URL here"
        
        # Extract authorization code from URL
        $uri = [System.Uri]$redirectResponse
        $queryParams = [System.Web.HttpUtility]::ParseQueryString($uri.Query)
        $authCode = $queryParams["code"]
        
        if (-not $authCode) {
            throw "Could not extract authorization code from URL"
        }
        
        # Exchange code for token (include client_secret for confidential client)
        $body = @{
            grant_type    = "authorization_code"
            client_id     = $ClientId
            client_secret = $ClientSecret
            code          = $authCode
            redirect_uri  = $RedirectUri
            scope         = $scope
        }
        
        $response = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"
        return $response.access_token
    }
    
    # -----------------------------------------------------------------------------
    # Main Script
    # -----------------------------------------------------------------------------
    
    # ===== OPTION A: Admin Center API (S2S) =====
    Write-Host "===== Option A: Admin Center API (S2S) =====" -ForegroundColor Cyan
    Write-Host "Acquiring S2S access token..." -ForegroundColor Yellow
    $tokenS2S = Get-BCAccessToken -TenantId $tenantId -ClientId $clientId -ClientSecret $clientSecret
    Write-Host "S2S token acquired!" -ForegroundColor Green
    
    $headersS2S = @{
        "Authorization" = "Bearer $tokenS2S"
        "Content-Type"  = "application/json"
    }
    
    $environmentsUrlA = "https://api.businesscentral.dynamics.com/admin/v2.28/applications/businesscentral/environments"
    Write-Host "Fetching environments from Admin Center API..." -ForegroundColor Yellow
    $environmentsA = Invoke-RestMethod -Uri $environmentsUrlA -Headers $headersS2S -Method Get
    
    Write-Host "`nEnvironments found (Admin Center API): $($environmentsA.value.Count)" -ForegroundColor Green
    Write-Host "============================================================"
    
    foreach ($env in $environmentsA.value) {
        Write-Host "`nEnvironment:  $($env.name)" -ForegroundColor Cyan
        Write-Host "  Type:         $($env.type)"
        Write-Host "  Country:      $($env.countryCode)"
        Write-Host "  Web Client:   $($env.webClientLoginUrl)"
    }
    
    # ===== OPTION B: Environments v1.1 API (Delegated) =====
    Write-Host "`n===== Option B: Environments v1.1 API (Delegated) =====" -ForegroundColor Cyan
    Write-Host "This endpoint requires delegated (user) permissions." -ForegroundColor Yellow
    
    $tokenDelegated = Get-BCDelegatedAccessToken -TenantId $tenantId -ClientId $clientId -ClientSecret $clientSecret -RedirectUri $redirectUri -LoginHint $userEmail
    Write-Host "Delegated token acquired!" -ForegroundColor Green
    
    $headersDelegated = @{
        "Authorization" = "Bearer $tokenDelegated"
        "Content-Type"  = "application/json"
    }
    
    $environmentsUrlB = "https://api.businesscentral.dynamics.com/environments/v1.1"
    Write-Host "Fetching environments from v1.1 API..." -ForegroundColor Yellow
    $environmentsB = Invoke-RestMethod -Uri $environmentsUrlB -Headers $headersDelegated -Method Get
    
    Write-Host "`nEnvironments found (v1.1 API): $($environmentsB.value.Count)" -ForegroundColor Green
    Write-Host "============================================================"
    
    foreach ($env in $environmentsB.value) {
        Write-Host "`nEnvironment:  $($env.name)" -ForegroundColor Cyan
        Write-Host "  Type:         $($env.type)"
        Write-Host "  Country:      $($env.countryCode)"
        Write-Host "  Web Client:   $($env.webClientLoginUrl)"
    }
    
     

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Small and medium business | Business Central, NAV, RMS

#1
OussamaSabbouh Profile Picture

OussamaSabbouh 2,362

#2
YUN ZHU Profile Picture

YUN ZHU 867 Super User 2025 Season 2

#3
Sumit Singh Profile Picture

Sumit Singh 607

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans