Skip to main content

Notifications

Small and medium business | Business Central, N...
Suggested answer

POST API Request - Business Central

Posted on by
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;
 
Categories:
  • Suggested answer
    Timos Tsamis Profile Picture
    Timos Tsamis on at
    POST API Request - Business Central
    Done! Just put transmissionType: 0, not '0'. 
  • Timos Tsamis Profile Picture
    Timos Tsamis 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
    Khushbu Rajvi. Profile Picture
    Khushbu Rajvi. 4,553 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

  • Suggested answer
    YUN ZHU Profile Picture
    YUN ZHU 73,565 Super User 2024 Season 2 on at
    POST API Request - Business Central
    Have you tested it in Postman? This shouldn't be an authentication issue.
     
    Thanks.
    ZHU

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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans