Blog
Blog

Building Robust Custom APIs in Microsoft Dynamics 365 Business Central (AL)

Posted on 22-May-2026 by Shrey Chauhan Associate Technical Consultant

Validation, Structured Responses & Error Logging Best Practices

Integrating external systems with Microsoft Dynamics 365 Business Central has become essential for modern businesses. Whether you're connecting payment gateways, CRMs, mobile apps, or third-party platforms, building reliable and scalable custom APIs in AL is critical for maintaining data integrity and seamless operations.

A well-designed custom API in Business Central should not only insert data but also validate requests, handle errors gracefully, return structured responses, and maintain audit logs for troubleshooting and monitoring.

In this blog, we’ll walk through a production-grade API architecture in AL that helps developers build secure, scalable, and enterprise-ready integrations.

 Why Custom APIs Matter in Business Central

Custom APIs in Business Central allow organizations to:

Integrate external applications securely

Automate data exchange

Maintain centralized business logic

Prevent duplicate or invalid records

Improve traceability and debugging

Without proper validation and logging mechanisms, APIs can easily become unstable and difficult to maintain in production environments.

API Architecture in Business Central (AL)

A scalable API Codeunit should follow a layered architecture for better maintainability and debugging.

 Recommended API Structure

Public Entry Point

procedure CreateDonation(JsonText: Text): Text

Core Processing Using TryFunction

[TryFunction] procedure CreateDonationFromJson(...)

Mapping Layer

local procedure TryMapJsonToDonation(...)

 Validation Layer

local procedure ValidateForCreate(...)

Error Logging Layer

local procedure LogError(...)

This modular design keeps the code clean, reusable, and easier to troubleshoot.

Handling JSON Input Properly in AL

When building APIs in Business Central, always treat incoming JSON as untrusted data.

 Validate JSON Structure

if not JArray.ReadFrom(JsonText) then Error('Invalid JSON. Expected an array of donation objects.');

 Process Records One at a Time

for i := 0 to JArray.Count() - 1 do begin JArray.Get(i, JToken); JObject := JToken.AsObject(); end;

Best Practice

Always isolate processing per record so one failed transaction does not impact the entire request.

Mapping JSON to Business Central Records

Instead of directly assigning values, use the Validate() method to trigger Business Central’s built-in business logic.

Example

DonTrans.Validate("Donation Modes", JToken.AsValue().AsCode()); DonTrans.Validate(Amount, JToken.AsValue().AsDecimal());

Why Use Validate()?

Using Validate() ensures:

Field validations execute correctly

Business rules are enforced

Table triggers run automatically

Data consistency is maintained

This is one of the most important API best practices in AL development.

 Implementing Strong Validation in Business Central APIs

A robust API should validate data at multiple levels before insertion.

 Mandatory Field Validation

if not JObject.Get('transactionDate', JToken) then Error('transactionDate is Required.');

 Business Rule Validation

if DonTrans.Amount <= 0 then Error('Donation amount must be greater than zero.');

Master Data Validation

DonMode.SetRange(Code, DonTrans."Donation Modes"); DonMode.SetRange("Is Active", true); if DonMode.IsEmpty() then Error('Invalid Donation Mode: %1.', DonTrans."Donation Modes");

Duplicate Validation

if DonTransExist.FindFirst() then Error( 'Duplicate uniqueTransactionId detected. Transaction ID %1 already exists with Entry No. %2.', UniqueTxnId, DonTransExist."Entry No.");

Writing User-Friendly API Error Messages

Generic error messages make debugging difficult.

 Avoid Generic Errors

 Bad Example

Error('Invalid data');

 Better Example

Error('%1 is required.', 'customerName');

 Production-Ready Example

Error( 'Duplicate TransactionReferenceNo detected. Reference No. %1 already exists with Entry No. %2.', UniqueTxnId, DonTransExist."Entry No.");

 API Error Message Best Practices

Always include:

Field name

Validation context

Suggested corrective action

Every API error should be actionable and easy to understand.

Returning Structured JSON Responses

Instead of returning plain text responses, always return structured JSON.

Example API Response

ResponseObj.Add('status', 'SUCCESS'); ResponseObj.Add('entryNos', EntryNoList); ResponseObj.WriteTo(ResponseText); exit(ResponseText);

 Sample Output

{ "status": "SUCCESS", "entryNos": "101,102,103" }

Recommended Response Enhancements

You can further improve your API response by adding:

errorCode

message

timestamp

correlationId

Structured responses improve API usability for external systems and frontend applications.

 Safe API Execution Using TryFunction in AL

Using [TryFunction] helps prevent unhandled exceptions from crashing API requests.

Example

[TryFunction] local procedure TryCreateDonation(...)

 Controlled Error Handling

if not TryCreateDonation(DonTrans) then Error(GetLastErrorText());

Why TryFunction Is Important

TryFunction enables:

Controlled exception handling

Stable API execution

Cleaner integration behavior

Better debugging

This is essential for enterprise-grade Business Central integrations.

 API Error Logging in Business Central

Error logging is a critical component of production-ready APIs.

Why Error Logging Matters

A proper logging system helps with:

Debugging failed requests

Audit tracking

Reprocessing failed transactions

Production monitoring

Example Error Logging

ErrLog.Init(); ErrLog."Date Time" := CurrentDateTime(); ErrLog.Operation := Operation; ErrLog."Payload Entry No." := PayloadEntryNo; ErrLog."Error Message" := CopyStr(GetLastErrorText(), 1, 2048); ErrLog."Raw Error JSON" := CopyStr(RawPayload, 1, MaxStrLen(...)); ErrLog.Insert(true);

 What Should You Log?

FieldPurpose

OperationIdentifies failed stage

Payload Entry NoTracks record reference

Error MessageStores actual exception

Raw JSONCaptures incoming payload

A well-designed logging mechanism makes APIs support-ready and easier to maintain.

 Business Central API Best Practices

If your API implementation already includes the following, you're following enterprise-grade design principles:

Using Validate() instead of direct assignment

Separating mapping and validation layers

Handling duplicate transactions

Using TryFunction

Returning structured JSON responses

Implementing centralized error logging

These practices significantly improve API reliability and scalability.

 Advanced Enhancements for Enterprise APIs

To further strengthen your Business Central API architecture, consider implementing the following:

 Add Response Wrapper Structure

{ "status": "ERROR", "message": "...", "details": [...] }

 Partial Success Handling

Process all records individually and return:

Successful records

Failed records

Validation details

Correlation ID Tracking

Assign a unique ID to every API request for end-to-end traceability.

 Idempotency Support

Prevent duplicate processing for repeated API calls.

These enhancements are highly valuable for high-volume integrations and enterprise deployments.

 Final Thoughts

Building a robust API in Microsoft Dynamics 365 Business Central is not just about inserting records into tables.

A production-ready API should ensure:

 Data integrity

 Complete traceability

 Controlled error handling

 Reliable system integrations

 Scalability for enterprise workloads

By implementing structured validation, TryFunctions, custom JSON responses, and centralized error logging, developers can build secure and scalable Business Central APIs that perform reliably in real-world business environments.


Post a Comment

Your email address will not be published. Required fields are marked (*)

Captcha
can't read? refresh

WhatsApp Now