MSBA-342 · Lesson 3 of 12 · 21 min
Custom services
▶ Video coming soon A video version of this lesson is on the way.
Two days after the OData clinic, the Prairieline portal team sent a second request. When a customer phoned about a leaking seal, the distributor's service desk wanted to type a serial number and see a single answer: is this pump covered, until when, for which parts, and has a claim already been paid on it? Then, if it was covered, the service desk wanted to submit a claim with a photo reference and the failed part, and get back a claim number. Prudence started sketching three new entities. Desmond stopped her. The request was not for data in rows; it was for a business operation with a question and an answer. That is what custom services are for.
This clinic covered how custom services are built, deployed and called; how they differ from OData; the data contracts that define their requests and responses; and the security and error-handling patterns that keep them maintainable. It also looked at the older SOAP endpoint, which still exists, and at the way the Power Platform can call a custom service through a connector.
Services, service groups and operations
A custom service exposes X++ class methods as web operations. It is built from three kinds of metadata. The service class is an ordinary X++ class whose public methods do the work. The service element names the class and lists which of its methods are published as service operations. The service group element bundles one or more services together for deployment. Every service must belong to a service group, and all service groups in the application's service group node are deployed automatically when the package is deployed. Once deployed, each service group is available on two endpoints: a JSON endpoint and a SOAP endpoint.
The JSON endpoint follows a fixed URL pattern: the environment URL, then api, services, the service group name, the service name and the operation name, separated by forward slashes. A client calls an operation with an HTTP POST and a JSON body whose property names match the method's parameter names. A GET request to the service group or service URL returns a list of its services or operations, which is a quick way to check that deployment worked. The SOAP endpoint lives under soap, services and the service group name, and publishes a WSDL document for clients that need one; Microsoft describes SOAP services as working the same way they did in Dynamics AX 2012. New integrations at Cobalt Ridge would use JSON.
Service group CRWarrantyServices
Service CRWarrantyInquiryService
Class CRWarrantyInquiryServiceClass
Operations getCoverage, submitClaim
JSON endpoints
GET https://cobaltridge-uat.operations.dynamics.com/api/services/CRWarrantyServices
POST https://cobaltridge-uat.operations.dynamics.com/api/services/CRWarrantyServices/CRWarrantyInquiryService/getCoverage
POST .../api/services/CRWarrantyServices/CRWarrantyInquiryService/submitClaim
SOAP endpoint (WSDL)
https://cobaltridge-uat.operations.dynamics.com/soap/services/CRWarrantyServices?wsdlData contracts
Operations exchange data through data contracts: classes that hold the parameters of a request or the fields of a response. A data contract class carries the DataContract attribute, and each of its parm methods carries the DataMember attribute with the name that appears in JSON. Contracts can contain simple types, enums, dates, other contracts and lists. A list of contracts needs to declare the type of its items, which is done with the AifCollectionTypeAttribute on the parm method, so that the serializer knows what each element is. Desmond preferred contracts to long parameter lists even for small operations, because adding a field to a contract later does not break existing callers, whereas adding a parameter to a method does.
[DataContract]
class CRWarrantyCoverageRequest
{
str serialNumber;
str legalEntity;
[DataMember('SerialNumber')]
public str parmSerialNumber(str _v = serialNumber)
{
serialNumber = _v;
return serialNumber;
}
[DataMember('LegalEntity')]
public str parmLegalEntity(str _v = legalEntity)
{
legalEntity = _v;
return legalEntity;
}
}
[DataContract]
class CRWarrantyCoverageResponse
{
boolean covered;
TransDate endDate;
str status;
List coveredParts = new List(Types::String);
boolean claimPaid;
[DataMember('Covered')]
public boolean parmCovered(boolean _v = covered) { covered = _v; return covered; }
[DataMember('EndDate')]
public TransDate parmEndDate(TransDate _v = endDate) { endDate = _v; return endDate; }
[DataMember('Status')]
public str parmStatus(str _v = status) { status = _v; return status; }
[DataMember('CoveredParts'), AifCollectionTypeAttribute('return', Types::String)]
public List parmCoveredParts(List _v = coveredParts) { coveredParts = _v; return coveredParts; }
[DataMember('ClaimPaid')]
public boolean parmClaimPaid(boolean _v = claimPaid) { claimPaid = _v; return claimPaid; }
}The service class
The service class itself is plain X++. Each published method takes contracts and returns a contract. The class should be thin: it unpacks the request, changes company if the request names a legal entity, calls the business logic that already exists in the warranty service and calculator classes, and packs the answer. Keeping business logic out of the service class means the same rules run when a person uses the form, when a batch job runs, and when the portal calls.
class CRWarrantyInquiryServiceClass
{
public CRWarrantyCoverageResponse getCoverage(CRWarrantyCoverageRequest _request)
{
CRWarrantyCoverageResponse response = new CRWarrantyCoverageResponse();
changecompany(_request.parmLegalEntity())
{
CRPumpWarrantyTable warranty =
CRPumpWarrantyTable::findBySerial(_request.parmSerialNumber());
if (!warranty)
{
throw error(strFmt("@CRCustom:SerialNotFound", _request.parmSerialNumber()));
}
response.parmCovered(CRPumpWarrantyCalculator::isCovered(warranty, DateTimeUtil::getToday(DateTimeUtil::getUserPreferredTimeZone())));
response.parmEndDate(warranty.EndDate);
response.parmStatus(enum2Symbol(enumNum(CRWarrantyStatus), warranty.Status));
response.parmCoveredParts(CRPumpWarrantyService::coveredParts(warranty.ItemId));
response.parmClaimPaid(CRWarrantyClaimTable::existsPaid(warranty.SerialNumber));
}
return response;
}
}Note how the status is returned as the enum symbol rather than the integer value. A number such as 2 means nothing to the portal and would silently change meaning if someone reordered the enum; the symbol Active is stable and readable. The same rule applies to business events in lesson 5.
When the portal calls the operation, it sends a JSON body whose top-level property name is the parameter name of the method, including the leading underscore, and whose value is the contract. The response body is the serialized return contract. Prudence found this the most surprising detail of the clinic; the first test call returned an error until she wrapped the request in the parameter name.
POST .../api/services/CRWarrantyServices/CRWarrantyInquiryService/getCoverage
Authorization: Bearer eyJ0eXAiOi...
Content-Type: application/json
{ "_request": { "SerialNumber": "MC-150-26-00412", "LegalEntity": "crca" } }
HTTP/1.1 200 OK
{ "Covered": true, "EndDate": "2028-11-12T12:00:00Z", "Status": "Active",
"CoveredParts": ["Impeller", "Casing", "Mechanical seal"], "ClaimPaid": false }Security for custom services
Custom services are secured through the same privileges as everything else, but there is a difference from entities: the wizard does not create privileges for you. A privilege grants access to a service operation through its entry points, and the security role of the integration user must contain that privilege. Desmond created CRWarrantyInquiryServiceInvoke for the coverage check and CRWarrantyClaimSubmit for claim submission, then added both to the CR Distributor warranty integration role from the previous clinic. The service class also checks inside its logic that the claim's customer matches the distributor's customer account, because a privilege says what an integration can call, not which records it may touch.
Authentication is identical to OData: a Microsoft Entra ID token for an app registration whose client ID is mapped to an application user. The same integration user can call both the warranty entity and the inquiry service, and the same throttling rules apply to both, because Microsoft's service protection limits cover OData and custom service endpoints alike.
Errors and transactions
When a service operation throws an error, the framework rolls back the transaction and returns an HTTP error status with the Infolog messages in the body. That is usually what the caller wants: a clear failure with a reason. Desmond added two habits. First, validation errors should use labels with plain-language messages, because those messages will appear on a distributor's screen. Second, submitClaim should be idempotent where possible: the portal sends its own claim reference, and if the same reference arrives twice, perhaps because the portal retried after a network timeout, the service returns the existing claim number instead of creating a duplicate. Retrying is normal in integration, as lesson 11 explains, so every write operation must be safe to repeat.
| Question | OData entity | Custom service |
|---|---|---|
| Shape of the work | Create, read, update, delete rows | Run a business operation with a request and a response |
| Code needed | Entity only; endpoint is automatic | Service class, contracts, service and group elements |
| Query flexibility | Callers filter, select and page freely | Only what the operation accepts |
| Logic placement | Entity and table methods | Service class calling business classes |
| Privileges | Generated with the entity | Created by the developer |
| Typical Cobalt Ridge use | Register a warranty | Check coverage; submit a claim |
Calling custom services from the Power Platform
The Power Platform can reach finance and operations apps in several ways, which lesson 10 compares. The standard Fin and Ops Apps connector in Power Automate and Power Apps works with entities: it lists, gets, creates, updates and deletes records and can execute OData actions such as the void action from the last clinic. To call a custom service operation, a maker uses a custom connector that describes the JSON endpoint with an OpenAPI definition and signs in through Microsoft Entra ID. Desmond showed both briefly, then noted that for a Cobalt Ridge maker the virtual entity route in lesson 7 was usually simpler for data, and that the connector route was best kept for operations like the coverage check.
Testing and versioning
A custom service is a contract with an outside party, so changing it carelessly breaks someone else's software. Desmond's rules were simple. Never rename or remove a published operation or DataMember; add new ones instead. Add new optional fields to contracts rather than changing the meaning of existing ones. If an operation must change incompatibly, publish a second operation with a version suffix, such as submitClaimV2, and retire the first only after the caller has moved. He also wrote SysTest unit tests that call the service class directly with contract objects, so that the logic could be tested without HTTP, and kept a small collection of example requests in the repository for manual tests against the UAT sandbox.
Designing the claim operation
The coverage check only read data. Claim submission wrote it, and Desmond walked through its design step by step because write operations carry more risk. The request contract held the portal's claim reference, the serial number, the legal entity, the failed part, the failure date, a short description of up to five hundred characters, and a list of photo references stored in the portal's own document store. The response contract held the Cobalt Ridge claim number, the claim status and a list of messages. The operation would validate the request, check coverage with the same calculator that the coverage operation used, create the claim header and its part line inside one transaction, attach the photo references as document links, and return.
Three questions took most of the discussion. The first was what to do when the pump was out of warranty. The portal team wanted an error; Annelise wanted the claim recorded anyway with a status of Out of warranty, because goodwill repairs were sometimes approved and the history mattered for supplier recovery. The service followed Annelise: it created the claim and returned a status the portal could show. The second was size. Photos would stay in the portal, not travel in the request, because a custom service is not a file-transfer channel and large payloads slow every caller on the same web server. The third was approval. Claims above a threshold set per company in the warranty parameters would enter the warranty claim approval workflow, which Prudence had learned to build in the extension course; the service would only submit, never approve, in the same way that Cobalt Ridge's agents may draft or submit but never post.
Desmond also asked Prudence to decide how the operation would behave under load. A distributor service desk might submit a few dozen claims on a busy day, so performance was not a concern for the operation itself. The concern was the coverage check, which the portal would call every time a service agent opened a customer record. He asked her to make sure the check used indexed lookups only, returned in well under a second in the UAT sandbox, and did not call the claim table with a query that scanned every claim. Prudence added an index on the claim table by serial number and status, and the test call dropped from nine hundred milliseconds to under one hundred.
Logging and support
Every call to a custom service shows up in the environment's telemetry, but the business view of what happened is often more useful to the support team. Desmond added a small log table, CRIntegrationLog, written by the service class at the end of each call with the operation, the caller's client ID, the claim reference, the result and the duration. The log was purged after ninety days by the cleanup batch job from the extension course. It gave the support desk a way to answer the most common question from a distributor, which is whether a call ever arrived, without asking a developer to search telemetry.
Worked problem
Entity or service?
Three new requests arrive. (1) The plant quality system wants to read inspection certificates recorded in the last day. (2) Prairieline wants to submit a warranty claim and get a claim number. (3) The finance team wants a monthly list of all claims paid. Which tool fits each?
Show solution
- Reading certificates is row-oriented reading with a filter on a date, a natural fit for an OData entity over the certificate table, or better, a business event (lesson 5) so the quality system is told rather than polling.
- Submitting a claim is a business operation that validates, creates several records and returns a number. A custom service operation fits, made idempotent with the portal's own claim reference.
- A monthly list of paid claims is analytics, not integration. It belongs in the Fabric-based reporting in lesson 9, or a data management export if a file is needed.
Answer: Entity or business event for certificates, custom service for claims, analytics or an export for the monthly list.
Common mistakes
MistakePutting business rules inside the service class.
InsteadKeep the service class thin and call the business classes that the forms and batch jobs also use.
MistakeReturning enum integers in responses.
InsteadReturn enum symbols, which stay stable and readable.
MistakeForgetting to create privileges for the service operations.
InsteadCreate privileges for each operation and add them to the integration role.
MistakeRenaming a published DataMember to tidy the JSON.
InsteadTreat published names as a contract; add new members instead of renaming.
Summary and key terms
- A custom service is a service class, a service element that publishes operations, and a service group that deploys them.
- Each service group is available on a JSON endpoint under api services and a SOAP endpoint under soap services.
- Data contracts with DataContract and DataMember attributes define requests and responses; lists declare their item type.
- Callers authenticate with Entra ID like OData; developers create the privileges for operations themselves.
- Keep service classes thin, write operations idempotent, and version contracts by adding rather than changing.
- Custom service
- X++ class methods published as web operations through a service and service group.
- Service group
- A metadata element that bundles services for automatic deployment to the JSON and SOAP endpoints.
- Service operation
- A method of a service class that is published for callers.
- Data contract
- A class with DataContract and DataMember attributes that carries request or response data.
- Idempotent operation
- An operation that produces the same result when the same request is repeated.
- JSON endpoint
- The REST endpoint for custom services under api services, called with HTTP POST.
Practice problems
Work each problem on paper first, then reveal the answer to check.
What is wrong with the request body {"SerialNumber": "MC-150-26-00412"} for the getCoverage operation?
Show answer
It is not wrapped in the parameter name; the body must be keyed by _request with the contract as its value.
Why should submitClaim accept the portal's own claim reference?
Show answer
So a retried call with the same reference returns the existing claim instead of creating a duplicate.
Which elements must be deployed for a new operation to appear at the JSON endpoint?
Show answer
The service class method, the service element listing it as an operation, and a service group containing the service.
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.