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

Community site session details

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

POST API Request - Business Central

(1) ShareShare
ReportReport
Posted on by 18
Hello Community,

I am trying to post a Sales Invoice as a json with a HTTP Request and I get a 400 Bad Request response. Authorization process works and I get jwt. Also checked the url (Path) and it is ok.
Any suggestions?

My code:
 
codeunit 52101 "Invoice Poster"
{
    [ServiceEnabled]
    procedure SendInvoice(InvoiceHeader: Record "Sales Header"): Boolean
    var
        JwtToken: Text;
        JsonString: JsonObject;
        InvNo: Code[20];
        Authentication: Codeunit "Authentication";
        InvoiceCreator: Codeunit "Invoice Creator";
    begin
        // Step 1: Authenticate and get the JWT token
        JwtToken := Authentication.Authenticate();  // Call the Authenticate procedure from codeunit 52100

        if JwtToken = '' then
            Error('Authentication failed. No JWT token received.');

        // Step 2: Create the invoice JSON
        JsonString := InvoiceCreator.CreateB2BInvoiceJson(InvoiceHeader);

        // Step 3: Post the generated JSON to the provider
        PostInvoiceJson(InvoiceHeader, JwtToken, InvNo, '', '0', JsonString);  // Send the JSON data to the provider
    end;
	
	procedure PostInvoiceJson(InvoiceHeader: Record "Sales Header"; Jwt: Text; InvNo: Code[20]; TemplID: Text; TransmType: Text; JsonString: JsonObject)
    var

        Client: HttpClient;
        Content: HttpContent;
        RequestContentMessage: HttpRequestMessage;
        Response: HttpResponseMessage;
        ContentHeaders: HttpHeaders;
        IsSuccessful: Boolean;

        JsonResponse: InStream;
        JsonResponse: Text;

        JsonObject: JsonObject;
        Token: JsonToken;
        RequestBody: InStream;
        Path: Text;
        AuthString: Text;

        InvoiceSetup: Record "E-Invoice Setup";
        ProvidersResponse: Record "Providers Response";

        Authentication: Codeunit "Authentication";
        InvoiceCreator: Codeunit "Invoice Creator";
        LogResponse: Codeunit "Log Response";
        LogResponseTimer: Codeunit "Log Status";

        TempBlob: Codeunit "Temp Blob";
        OutStream: OutStream;
        InStream: InStream;
        JsonText: Text;

        HttpStatusCode: Integer;
        ResponseText: Text;
		
    begin
	
		// Call the CreateB2BInvoiceJson procedure to create JSON Invoice
        Clear(JsonString);
        JsonString.Add('invoice', InvoiceCreator.CreateB2BInvoiceJson(InvoiceHeader));
        

        // Serialize the nested JSON object to a string
        Clear(TempBlob);
        Clear(OutStream);
        Clear(InStream);
        TempBlob.CreateOutStream(OutStream);
        JsonString.WriteTo(OutStream);
        TempBlob.CreateInStream(InStream);
        InStream.ReadText(JsonText);
        Message('Serialized JSON: %1', JsonText);

        InvNo := InvoiceCreator.GetInvoiceNo(InvoiceHeader);

        // Create the Request body including JSON Invoice
        Clear(JsonObject);
        TemplID := 'eInvoicing';
        //JsonObject.Add('processID', '');
        JsonObject.Add('externalSystemId', InvNo);
        JsonObject.Add('identifier', TemplID);
        JsonObject.Add('transmissionType', TransmType);
        //JsonObject.Add('source', JsonText);
        JsonObject.Add('source', JsonString);

        Clear(TempBlob);
        Clear(OutStream);
        TempBlob.CreateOutStream(OutStream);
        JsonObject.WriteTo(OutStream);
        TempBlob.CreateInStream(RequestBody);
		
        JsonObject.WriteTo(RequestBody);

        RequestContentMessage.Content(Content);
        RequestContentMessage.Method := 'POST';
        //RequestContentMessage.Method('POST');

        // Add necessary headers (such as Content-Type and Method)
        Content.GetHeaders(ContentHeaders);
		
        AuthString := StrSubstNo('Bearer %1', jwt);
		
        Client.DefaultRequestHeaders.Remove('Authorization');
        Client.DefaultRequestHeaders.Add('Authorization', AuthString);
		
        if ContentHeaders.Contains('Content-Type') then ContentHeaders.Remove('Content-Type');
        ContentHeaders.Add('Content-Type', 'application/json');
        if ContentHeaders.Contains('X-Version') then ContentHeaders.Remove('X-Version'); //! Necessary Header by documentation
        ContentHeaders.Add('X-Version', '3.0');
        //if ContentHeaders.Contains('Content-Encoding') then ContentHeaders.Remove('Content-Encoding');
        //ContentHeaders.Add('Content-Encoding', 'UTF8');

        // Send the POST request with the JSON data
        ProvidersResponse.Reset();
        ProvidersResponse.SetRange(jwt, jwt);
        if ProvidersResponse.FindSet() then begin
            Clear(Path);
            if InvoiceSetup.FindFirst() then
                Path := StrSubstNo('%1%2', ProvidersResponse."URL1", InvoiceSetup."Send Request");
        end;
		
        RequestContentMessage.SetRequestUri(Path);
        Content.WriteFrom(RequestBody);
		
		//Client.Post(Path, Content, Response);
        IsSuccessful := Client.Post(Path, Content, Response);
		
        if not IsSuccessful then begin// handle the errorend;         
            if not Response.IsSuccessStatusCode() then begin
                HttpStatusCode := response.HttpStatusCode();
                // handle the error (depending on the HTTP status code)
            end;
            Response.Content().ReadAs(ResponseText);
        end;
    end;
 
I have the same question (0)
  • Suggested answer
    YUN ZHU Profile Picture
    93,197 Super User 2025 Season 2 on at
    POST API Request - Business Central
    Have you tested it in Postman? This shouldn't be an authentication issue.
     
    Thanks.
    ZHU
  • Suggested answer
    Khushbu Rajvi. Profile Picture
    19,353 Super User 2025 Season 2 on at
    POST API Request - Business Central
    You can recommend a blog, and once it gets approved, its posts will automatically appear in the blog section

  • Timos Tsamis Profile Picture
    18 on at
    POST API Request - Business Central
    Tried in Postman and it works. It seems strange because the code appears well-structured for creating a JSON object so I cannot understand why I get a Bad Request.
  • Suggested answer
    Timos Tsamis Profile Picture
    18 on at
    POST API Request - Business Central
    Done! Just put transmissionType: 0, not '0'. 

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…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

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

#1
Rishabh Kanaskar Profile Picture

Rishabh Kanaskar 2,828

#2
Sumit Singh Profile Picture

Sumit Singh 2,617

#3
YUN ZHU Profile Picture

YUN ZHU 1,861 Super User 2025 Season 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans