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...
Answered

Custom Api - Deep Insert

(1) ShareShare
ReportReport
Posted on by 111
I am developing a custom apipage  which follows a header / lines pattern as such following the example I am able to create a PART page on the header api so I can make a deep insert. This works as expected.
 
Question: I want to verify on the validation code that the sum of the line quantities equal the totalquantity value in the header - how can i access the lineitems from the header record so i can verify that TotalQuantity equals the sum of the lines?  Is there a way to directy access the post jsonbody from the page triggers of the header?
 
Thanks so much!
 
Example
{
No: 1,
Name: order 1,
TotalQuantity: 12
[
{LineNumber:1, Qty: 5},
{LineNumber:2, Qty: 7}
}
I have the same question (0)
  • Suggested answer
    Nyakinyua Profile Picture
    55 on at
    This is the approach I'd take
     
    [EventSubscriber(ObjectType::Table, Database::<Table Name>, 'OnBeforeInsertEvent', '', <SkipOnMissingLicense>, <SkipOnMissingPermission>)]
        local procedure OnBeforeInsert(var Rec: Record "YourHeaderTable"; var xRec: Record "YourHeaderTable"; RunTrigger: Boolean)
        var
            JsonObject: JsonObject;
            LineItemsArray: JsonArray;
            LineItem: JsonObject;
            TotalQuantity: Integer;
            SumQty: Integer;
        begin
            // Parse the JSON body from the API request
            JsonObject := JsonObject.Parse(Rec.RequestBody);
     
            // Extract TotalQuantity from the header
            TotalQuantity := JsonObject.GetValue('TotalQuantity');
     
            // Extract LineItems array
            LineItemsArray := JsonObject.GetArray('LineItems');
            SumQty := 0;
     
            // Loop through LineItems and sum quantities
            foreach LineItem in LineItemsArray do begin
                SumQty += LineItem.GetValue('Qty');
            end;
     
            // Validate that the sum of quantities matches the TotalQuantity
            if SumQty <> TotalQuantity then
                Error('The sum of line quantities (%1) must equal the TotalQuantity (%2).', SumQty, TotalQuantity);
        end;
  • MH-06060002-0 Profile Picture
    111 on at
    Thanks so much for your reply - The issue is accessing the requestbody while utilizing the bultin in custom api design pattern. 
     
    Alternatively is the only way to do it to rewrite the API Part and parse the nested json manually for the line items?
     
    Thanks
  • Gerardo Rentería García Profile Picture
    26,091 Most Valuable Professional on at
  • Suggested answer
    YUN ZHU Profile Picture
    99,966 Super User 2026 Season 1 on at
    Hi, hope the following can give you some hints as well.
    Tips & Tricks for Creating Custom APIs
     
    Thanks.
    ZHU
  • Suggested answer
    MH-06060002-0 Profile Picture
    111 on at
    Thanks to everyone for their input: This is the way I was able to solve the problem while maintaining the built in design pattern, I wanted to share this as deep inserts are barely covered in the the built in documentation:
     
    The following Post Body
    {
        "no": 1907,
        "txtfield1": "header1",
        "testLines":[
            {"txtfield1":"Line1"},
            {"txtfield1":"Line2"}
            ]
    }
     
    Theis is the api page trigger sequence when inserting a header with 2 lines in a single post (deep insert)
    1    Header OnInit    
    2    Header OnOpenPage    
    3    Header OnNewRecord    
    4    Header OnValidate Field    (Could be multiple)
    5    Header OnInsertRecord    header1
    6    Line OnInit    
    7    Line OnNewRecord    
    8    Line OnValidate Field    (Could be multiple)
    9    Line OnInsertRecord    Line1
    10    Line OnNewRecord    
    11    Line OnValidate Field    (Could be multiple)
    12    Line OnInsertRecord    Line2
    13    Header OnAfterGetRecord    
    14    Header OnAfterGetCurrRecord    
     
    The key here is that the Header OnAfterRecord is run again at the bottom of the sequence and is used to send back the json reply to the post. As a result the secret to running code after the completion of the deep insert is as follows
     
    1) In Trigger 3 set  a page variable deepinsertinprocess to true (this is needed as the onaftergetrecord is also run during a get call and we only want certain behavior in the get call if it as a result of the post insert call)
    2) In Trigger 13 Header OnAfterGetRecord test if deepinsertinprocess is true and then conduct code - for example check if there are more than 2 lines.  At this point you can access the sublines as records that match the current Rec.  See below.  Since we are still in the current transaction scope the error we are raising will rollback the original insert!  This can also be used to run code after the completion of the entire post Header and Lines!
     
     trigger OnAfterGetRecord()
        var
            a: Record testapiLines;
            b: Record testapiHeader;
        begin
            if deepinsertinprocess then begin
                a.SetRange(a.HeaderLink, rec.SystemId);
                if a.FindSet() then begin
                    if a.Count <> 2 then
                        Error('Fail On line item count check');
                end;
            end;
        end;
     

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

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Meet the Microsoft Dynamics 365 Contact Center Champions

We are thrilled to have these Champions in our Community!

Congratulations to the March Top 10 Community Leaders

These are the community rock stars!

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

#1
OussamaSabbouh Profile Picture

OussamaSabbouh 1,831 Super User 2026 Season 1

#2
YUN ZHU Profile Picture

YUN ZHU 1,122 Super User 2026 Season 1

#3
Khushbu Rajvi. Profile Picture

Khushbu Rajvi. 690 Super User 2026 Season 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans