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

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

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

Unauthorised 401 Error Occurs Rest API in business Central

(0) ShareShare
ReportReport
Posted on by 99

Access Token generated successfuly....but Show error 401 Unauthorized.

pastedimage1658398391730v1.png

 var
        ClientIdTxt: Label 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
        ClientSecretTxt: Label 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
        AadTenantIdTxt: Label 'sandbox';
        AuthorityTxt: Label 'https://login.microsoftonline.com/bbXXXXXX-XXXX-XXXX-XXXX-XXXXXX/oauth2/v2.0/token';
        BCEnvironmentNameTxt: Label 'sandbox';
        BCCompanyIdTxt: Label 'bbexxxxxx-xxxx-xxxx-xxxx-xxxxxxxx5';
        // BCBaseUrlTxt: Label 'https://api.businesscentral.dynamics.com/v2.0/{BCEnvironmentName}/api/v2.0/companies({BCCompanyId})';
     
        AccessToken: Text;
        AccesTokenExpires: DateTime;
        contentHeaders: HttpHeaders;
        request: HttpRequestMessage;
        HttpContent: HttpContent;

    trigger OnRun()
    var
        Customers: Text;
        Items: Text;

    begin

        Customers := CallBusinessCentralAPI(BCEnvironmentNameTxt, BCCompanyIdTxt, 'ExcelTemplateViewCompanyInformation');
        // Items := CallBusinessCentralAPI(BCEnvironmentNameTxt, BCCompanyIdTxt, 'items');
        Message(Customers);
        Message(Items);
    end;

    procedure CallBusinessCentralAPI(BCEnvironmentName: Text; BCCompanyId: Text; Resource: Text) Result: Text
    var
        Client: HttpClient;
        Response: HttpResponseMessage;
        Url: Text;

        response1: Text;

    begin

        Url := 'https://api.businesscentral.dynamics.com/v2.0/bbexxxxxx-xxxx-xxxx-xxxx-xxxxxxxx5/Cronus/ODataV4/Company(CRONUS IN)/ExcelTemplateViewCompanyInformation';
        if (AccessToken = '') or (AccesTokenExpires = 0DT) or (AccesTokenExpires > CurrentDateTime) then
            GetAccessToken(AadTenantIdTxt);
        contentHeaders := Client.DefaultRequestHeaders();
        contentHeaders.Add('Authorization', GetAuthenticationHeaderValue(AccessToken));
        HttpContent.GetHeaders(contentHeaders);

        request.Content := HttpContent;
        request.SetRequestUri(Url);
    
        if not Client.Get(Url, Response) then begin
            if Response.IsBlockedByEnvironment then
                Error('Request was blocked by environment')
            else
                Error('Request to Business Central failed\%', GetLastErrorText());

        end;

        if not Response.IsSuccessStatusCode then
            Error('Request to Business Central failed\%1 %2', Response.HttpStatusCode, Response.ReasonPhrase);
        Response.Content.ReadAs(Result);
    end;

    local procedure GetAccessToken(AadTenantId: Text)
    var
        OAuth2: Codeunit OAuth2;
        Scopes: List of [Text];
    begin
        Scopes.Add('https://api.businesscentral.dynamics.com/.default');
        if not OAuth2.AcquireTokenWithClientCredentials(ClientIdTxt, ClientSecretTxt, GetAuthorityUrl(AadTenantId), '', Scopes, AccessToken) then
            Error('Failed to retrieve access token\', GetLastErrorText());
        AccesTokenExpires := CurrentDateTime   (3599 * 1000);
    end;


    local procedure GetAuthenticationHeaderValue(AccessToken: Text) Value: Text;
    begin
        Value := StrSubstNo('Bearer %1', AccessToken);
    end;

    local procedure GetAuthorityUrl(AadTenantId: Text) Url: Text
    begin
        Url := AuthorityTxt;
        Url := Url.Replace('{AadTenantId}', AadTenantId);
    end;

  • Suggested answer
    Chameera Kavinda Profile Picture
    510 on at

    Hi Sejal,

    Did you create an AAD Application in BC using the ClientId with the required permissions?

    Please go through the below documentation for better understanding.

    https://yzhums.com/20690/

    It's recommended to check your API using POSTMAN or any other application and verify all the thing are in line.

    Thank you.

  • Suggested answer
    divyeshchitte Profile Picture
    970 on at

    Can you use the URL in POST MAN ?

    Have you passed correct Headers in the API?

    Can you share a screen shot for which this API is working

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

Season of Sharing Community Challenge Winners!

Congratulations to our community stars!

Women in Power Builds Momentum

Expanding mentorship, skilling, and AI innovation

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

#1
OussamaSabbouh Profile Picture

OussamaSabbouh 645 Super User 2026 Season 2

#2
YUN ZHU Profile Picture

YUN ZHU 432 Super User 2026 Season 2

#3
Teagen Boll Profile Picture

Teagen Boll 248 Super User 2026 Season 2

Last 30 days Overall leaderboard

Featured topics

Microsoft Training Manuals

Product updates

Dynamics 365 release plans