MSBA-352 · Lesson 8 of 12 · 19 min
Queries and APIs
▶ Video coming soon A video version of this lesson is on the way.
Two new requests reached Joss in the second week of November. Ysmay Thorvaldsen, the roastery manager, also looks after the equipment side of the business, and she wanted to know which grinder models generate the most claims, by month, without exporting three lists to a spreadsheet and matching them by hand. And Corbel & Finch's web shop developer, an outside contractor, asked whether the shop's "check my warranty" form could look up a serial number in Business Central directly. Noor called them two sides of the same topic. "Ysmay needs to read joined, summarized data efficiently. The web shop needs to read and write data from outside, safely. In AL, the first is a query and the second is an API."
What a query is
A query object describes a dataset across one or more tables: which tables, how they join, which columns to return, which filters to apply, and how to group and total. Business Central turns it into a single SQL statement and runs it on the database. That is the key difference from looping over records in AL. A loop that reads registrations and then looks up each item and each claim makes many round trips to the database; a query makes one.
Queries are used in four ways. Code can run them with Open and Read, much faster than nested record loops. Pages and charts can use them as a data source. Users can open some queries directly or export their results. And a query with QueryType = API becomes a read-only web service.
Ysmay's claims query
namespace Quarrystone.CorbelFinch.Warranty;
using Microsoft.Inventory.Item;
query 50100 "CNF Claims by Item and Month"
{
Caption = 'Warranty Claims by Item and Month';
QueryType = Normal;
DataAccessIntent = ReadOnly;
OrderBy = descending(ClaimCount);
elements
{
dataitem(Claim; "CNF Warranty Claim")
{
column(ReportedYear; "Date Reported") { Method = Year; }
column(ReportedMonth; "Date Reported") { Method = Month; }
column(ClaimCount) { Method = Count; }
filter(DateFilter; "Date Reported") { }
dataitem(Registration; "CNF Warranty Registration")
{
DataItemLink = "Entry No." = Claim."Registration Entry No.";
SqlJoinType = InnerJoin;
dataitem(Item; Item)
{
DataItemLink = "No." = Registration."Item No.";
SqlJoinType = InnerJoin;
column(ItemNo; "No.") { }
column(ItemDescription; Description) { }
}
}
}
}
}The query reads from the inside out like a sentence: for each claim, find its registration, and for each registration, find its item. Each nested dataitem names its link to the one above with DataItemLink and the kind of join with SqlJoinType.
| SqlJoinType | Returns |
|---|---|
| InnerJoin | Only rows that match in both data items |
| LeftOuterJoin (the default) | Every row from the upper data item, with blanks where the lower has no match |
| RightOuterJoin | Every row from the lower data item, with blanks where the upper has no match |
| FullOuterJoin | Every row from both, matched where possible |
| CrossJoin | Every combination of rows; rarely what anyone wants |
Ysmay's question only concerns claims that have a registration and an item, so inner joins fit. If she had asked for every grinder model including those with no claims, the item would have to be the top data item with left outer joins down to registrations and claims, so that models with zero claims still appear.
Aggregation happens through the Method property on columns. Count, Sum, Average, Min and Max work as in SQL. When any column has an aggregate method, every other column becomes a grouping column, so this query returns one row per item, year and month. Year, Month and Day are date methods that extract part of a date, which is how the query groups by month without a separate field. OrderBy sorts the result with the most claimed items first.
The filter element adds a filter that does not appear as a column. Code can set it before opening the query, so the same query answers "claims this year" and "claims last quarter".
Running a query from code
procedure ShowTopClaimedItems(FromDate: Date; ToDate: Date)
var
ClaimsQuery: Query "CNF Claims by Item and Month";
Lines: TextBuilder;
Shown: Integer;
begin
ClaimsQuery.SetRange(DateFilter, FromDate, ToDate);
ClaimsQuery.TopNumberOfRows(5);
ClaimsQuery.Open();
while ClaimsQuery.Read() do begin
Lines.AppendLine(StrSubstNo(LineTxt, ClaimsQuery.ItemNo, ClaimsQuery.ItemDescription,
ClaimsQuery.ReportedMonth, ClaimsQuery.ReportedYear, ClaimsQuery.ClaimCount));
Shown += 1;
end;
ClaimsQuery.Close();
if Shown = 0 then
Message(NoClaimsMsg)
else
Message(Lines.ToText());
end;A query variable is used like a cursor: set filters, optionally limit rows with TopNumberOfRows, Open, Read in a loop, and Close. Columns are read as properties of the variable by their names in the query. Queries are read-only; they never insert or modify.
For Ysmay, Joss did not stop at a message. Queries with a query category can be offered from list pages, and their result can be opened in Excel or analysed further. In the end Ysmay got an Excel report built on the query, the same pattern as the expiry list in lesson 7, because she wanted a chart.
APIs: Business Central from the outside
Business Central exposes data to other systems through REST APIs that speak OData: a client sends HTTP requests to a URL and gets JSON back. Microsoft ships a standard set, the API v2.0 endpoints, for customers, items, vendors, sales orders, journals and dozens more. Corbel & Finch's web shop integration from earlier in the project already uses the standard salesOrders API to create orders.
Warranty registrations are new data, so there is no standard API for them. An extension can publish its own custom API with a page of type API (read and write) or a query of type API (read only).
namespace Quarrystone.CorbelFinch.Warranty;
page 50110 "CNF Warranty API"
{
PageType = API;
APIPublisher = 'quarrystone';
APIGroup = 'warranty';
APIVersion = 'v1.0';
EntityName = 'warrantyRegistration';
EntitySetName = 'warrantyRegistrations';
SourceTable = "CNF Warranty Registration";
ODataKeyFields = SystemId;
DelayedInsert = true;
InsertAllowed = false;
ModifyAllowed = false;
DeleteAllowed = false;
Extensible = false;
layout
{
area(Content)
{
repeater(Records)
{
field(id; Rec.SystemId) { Editable = false; }
field(serialNumber; Rec."Serial No.") { }
field(itemNumber; Rec."Item No.") { }
field(customerNumber; Rec."Customer No.") { }
field(startDate; Rec."Start Date") { }
field(endDate; Rec."End Date") { }
field(status; Rec.Status) { }
field(lastModifiedDateTime; Rec.SystemModifiedAt) { }
}
}
}
}The API properties build the URL. With APIPublisher quarrystone, APIGroup warranty and APIVersion v1.0, the endpoint for a company is under the tenant's and environment's API address, followed by api/quarrystone/warranty/v1.0/companies(id)/warrantyRegistrations. The client can filter with OData syntax, for example on serialNumber, and receives JSON with the camel-case field names Joss chose.
| Property or rule | Why |
|---|---|
| PageType = API | Makes the page a web service with no user interface |
| APIPublisher, APIGroup, APIVersion | Build the URL and let several versions live side by side |
| EntityName, EntitySetName | The singular and plural names in the URL and JSON |
| ODataKeyFields = SystemId | A stable GUID key that never changes, unlike numbers that can be renamed |
| DelayedInsert = true | Required on API pages so a record is inserted only once all fields are set |
| camelCase field names | The convention for JSON APIs; no spaces or punctuation |
| Insert, Modify, Delete allowed | Decide exactly which operations the API supports |
Noor insisted on two design decisions. First, the web shop gets read-only access: InsertAllowed, ModifyAllowed and DeleteAllowed are all false, because registrations are created only by posting. A read-only API could also have been a query with QueryType = API, but the page leaves room to add a writable claims API in the same group later. Second, the version is part of the URL from day one. When the API needs a breaking change, Quarrystone will publish v2.0 alongside v1.0, and the web shop will move when it is ready.
Who may call the API
An API is only as safe as the identity calling it. Business Central online accepts API calls authenticated with Microsoft Entra ID. For a system-to-system integration like the web shop, the usual approach is an app registration in Entra ID using the client credentials flow, registered in Business Central on the Microsoft Entra Applications page and given permission sets like a user. The web shop's app would get only the warranty read permission set from lesson 10, so even a leaked secret could not change or read anything else. Setting up the app registration, testing calls and handling throttling limits belong to the integration course that follows this one.
The web shop contractor also asked for a "register my machine" form where cafés could enter a serial number bought elsewhere. Noor said no for version 1: anything a public form writes must be validated, logged and rate limited, and that is a different project. The shop will show warranty status for machines Corbel & Finch sold, and nothing more.
APIs, OData pages and the old ways
Older integrations published ordinary pages and codeunits as SOAP or OData v4 web services from the Web Services page. These still work, and some partner tools rely on them, but Microsoft recommends API pages and queries for new integrations: they have stable URLs, versioning, camel-case JSON, and do not break when someone changes a page's layout for users. Joss's rule of thumb from Noor: user pages are for users, API pages are for machines, and never the other way round.
Choosing between a query, a report and an API
| Need | Best tool | Why |
|---|---|---|
| Totals across joined tables, used in code | Query | One database call, grouping and aggregation built in |
| A list or document for people to read or print | Report with a layout | Layouts, request pages, printing and Excel output |
| Another system reading or writing Business Central data | API page or API query | Versioned, authenticated, JSON over HTTP |
| A user browsing and filtering records | List page | Filtering, sorting, views and export built in |
Worked problem
Designing a join
Callum asks for every customer with active warranties and the number of open claims each has, including customers with none. Which data item is on top, and which join types are needed?
Show solution
- Every customer with active warranties must appear, so the registrations, filtered to Active, are the starting point, linked up to Customer for the name.
- Claims must be counted where they exist but must not remove customers without claims, so the claim data item joins with LeftOuterJoin.
- A Count column on the claim data item gives the number of claims; Customer No. and Name become grouping columns.
- A filter on claim status restricts the count to open claims. Because a left outer join with a filter on the lower table can drop rows, Joss tests the result with a customer who has no claims before trusting it.
Answer: Start from active registrations, join claims with a left outer join, count claims, and test the edge case of customers with none.
Use standard APIs first
Before writing an API, check whether a standard one already covers the need. The v2.0 APIs include customers, items, sales and purchase documents, journals, dimensions, attachments and many more, and Microsoft maintains them through every update. They also support $expand to fetch related records in one call, $filter for server-side filtering, and $select to return only some fields. For the web shop's needs, the standard salesShipments and item ledger data almost answered the warranty question, but not quite: they do not know about warranty periods or claims. Only that gap justified a custom API. Noor's advice was to keep custom APIs as narrow as the gap, so that most of an integration still runs on endpoints Quarrystone does not have to maintain.
Limits and good manners
Business Central online protects itself from heavy integrations with operational limits: a maximum number of concurrent requests per user, rate limits over time, a maximum page size for results, and timeouts. A client that exceeds them receives an HTTP 429 response and must wait before retrying. The web shop contractor's first design looked up warranty status every time a page loaded; Joss suggested caching the answer in the shop for a day, because warranty status changes rarely. Clients should also request only the fields they need, page through large results with the next link the API returns, and use webhooks, where Business Central notifies a subscriber when data changes, instead of polling. Webhooks, batch requests and bound actions on API pages belong to the next course.
Versioning an API
Once an outside system depends on an API, its URL, entity names and field names are a contract. Adding a field is safe. Renaming or removing one, or changing what a field means, breaks the web shop. The answer is a new API version: a second page with APIVersion v2.0 in the same group, published alongside v1.0, with v1.0 kept until every client has moved. Joss added a line to the app's documentation listing the API versions, their clients and their owners, so that nobody removes v1.0 in two years without knowing who still calls it.
Common mistakes
MistakeLooping over records and looking up related tables one by one for a summary.
InsteadUse a query to join and aggregate in one database call.
MistakeUsing inner joins when the question includes records with no matches.
InsteadUse a left outer join from the table whose rows must all appear.
MistakePublishing a user page as a web service for an integration.
InsteadWrite an API page or query with a versioned URL.
MistakeUsing a number field as the API key.
InsteadUse SystemId with ODataKeyFields.
MistakeGiving an integration a broad permission set because it is easier.
InsteadGrant only the permission sets the integration needs.
Summary and key terms
- A query defines joined, filtered and aggregated data that runs as one database statement.
- Data items nest with DataItemLink and SqlJoinType; Method sets aggregation and date grouping.
- Code runs queries with SetRange, Open, Read and Close; queries never write.
- Business Central exposes standard API v2.0 endpoints; extensions add custom API pages and queries.
- API pages need publisher, group, version, entity names, SystemId keys and DelayedInsert.
- Integrations authenticate through Entra ID and get only the permission sets they need.
- Query
- An object that reads joined and aggregated data in one database call.
- SqlJoinType
- The property that sets how a data item joins to the one above it.
- Method
- A column property for aggregation such as Count or Sum, or date parts such as Month.
- API page
- A page with PageType API that exposes data as a REST web service.
- APIVersion
- The version segment in a custom API's URL.
- ODataKeyFields
- The fields used as the key in API URLs, usually SystemId.
- Read scale-out
- Running read-only reports and queries on a read-only database replica.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why is Ysmay's query faster than looping over claims and getting each registration and item?
Show answer
The query runs as one SQL statement with joins and grouping; the loop makes a database call for every lookup.
Why is the warranty API read-only?
Show answer
Registrations are created only by posting, and the web shop only needs to show status.
What is the URL path segment that identifies Joss's API?
Show answer
api/quarrystone/warranty/v1.0, followed by the company and the entity set warrantyRegistrations.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.