Skip to content

Web Services - Guide ​

Who this page is for: developers who connect Salesforce to other systems, and the architects and business analysts who design, configure and monitor those integrations. New to it? Try Fast Start - Outbound APIs or Fast Start - Inbound APIs first: step-by-step walkthroughs that cover implementation, testing, and common pitfalls. Deciding whether to use KernDX? See Why KernDX.

Copy this first ​

apex
HttpResponse response = kern.UTIL_HttpClient.get('CRM', '/accounts/{id}')
	.pathParam('id', accountId)
	.send();

What this does: sends a GET request through the named credential CRM (the Salesforce setting that holds the other system's address and login) to /accounts/ followed by the account Id, and returns the answer. send() always returns a response: a status code of 0 means no answer came back.

Read next: More about this quick client, A full outbound integration, Receive calls from other systems, Test without calling out.


Quick Navigation ​

I need to...Go to...
Build outbound APIsBuilding Outbound APIs
Build inbound APIs, or receive a webhookBuilding Inbound APIs
Call an API from a FlowHow do I call it from a Flow?
Test without calling the real systemMock Mode and API_MockFactory
Find out why my call returned status code 0Status code is 0
Run a failed call againRunning a failed call again by hand
Turn an API off during an incidentDisabling APIs
Check who needs which permissionWho needs which permission?
Add an API key headerWhere credentials belong
Configure API settingsApiSetting__mdt
Monitor API healthLogging and Monitoring
Review advanced featuresWhat else can it do?
Understand API architectureHow does it work?
Understand the two-class inbound designInbound API Architecture
See why KernDX is worth usingWhy KernDX: the outbound calls and Flow actions examples

Quick Start ​

Pick the shape that fits your call:

Your callWhat to write
A one-off callNothing more: the one line under Copy this first (UTIL_HttpClient)
A reusable integration, with DTOs, validation or record savesA small class: API_Outbound for calls Salesforce makes out to another system, API_Inbound for calls another system makes into Salesforce (Building Inbound APIs). The outbound shape is below

Not sure which? See When to use UTIL_HttpClient vs API_Outbound.

apex
public inherited sharing class API_GetWeather extends API_Outbound
{
	public override void configure()
	{
		super.configure();
		requestPayload = new DTO_Request();
		responsePayload = new DTO_Response();
		defaultMockBody = '{"temperature": 72, "conditions": "Sunny"}';
	}
}

Namespaces in code samples: kern. on a class and kern__ on an object, field, or metadata type mark the managed package's namespace. On the managed package, framework references need those prefixes even where a sample omits them; repackaged under your own namespace, replace kern/kern__ with your prefix; on an unmanaged deploy, drop them. See How to read the code samples.

To run it: give the class an API Setting record (Step 3), then call UTIL_HttpClient.useHandler(API_GetWeather.class).invoke() from your code (Delegation mode).


What is it? ​

What is the Web Services Framework? ​

The Web Services Framework gives you one consistent way to handle both inbound (receiving) and outbound (sending) API integrations in Salesforce. You solve the common problems once and reuse the answer in every integration:

  • One shape for every REST integration, so a developer who learns one can read any other.
  • A kept record of every call in ApiCall__c, so a production failure leaves evidence to investigate instead of an expired debug log.
  • Retries that recover on their own (linear, exponential, or custom backoff), so a brief outage at the other end does not fail the user.
  • Sensitive data hidden before it is logged, so cards, tokens, and personal details never sit in plain text.
  • Fake responses for tests and demos, so you exercise integration logic without making real network calls.
  • Flow actions for admins, so an API can be called with no Apex.
  • Failure tracking, so repeated problems surface rather than passing unnoticed.
  • Per-stage timing on every call, so you can see which integrations are slow and where the time goes.
  • Reusable architecture you can distribute as a managed package across orgs.
  • Calls back into your own org, so Composite, Tooling, and custom REST endpoints work through the same pipeline.

Web Services Framework Scope: 16 API_* classes (4 extending API_Outbound), 10 DTO_* classes, 2 named credentials, and full lifecycle tracking via ApiCall__c and ApiIssue__c. Includes UTIL_HttpClient for zero-boilerplate callouts with automatic retry, circuit breaker, and failure logging.

Responsibilities: The Web Services framework handles HTTP callout orchestration (request building, execution, response parsing, logging, and retry). It does not contain business logic; that belongs in the calling code or trigger actions. DTOs transport data; API classes orchestrate the call lifecycle.

When not to use it: see Don't use this when.


UTIL_HttpClient (Fluent HTTP Client) ​

UTIL_HttpClient is the simplest way to make HTTP calls in KernDX: you do not have to write a whole API class first. Configure the call with a few short chained calls, then one call sends it.

It wraps the API_Outbound pipeline, so without writing a dedicated API class you still get:

  • automatic retry;
  • a circuit breaker you switch on with .withCircuitBreaker() (after repeated failures it stops calling a failing system for a cool-off, then resumes);
  • failure logging, performance timing, and data masking.

When to use UTIL_HttpClient vs API_Outbound:

ScenarioRecommended Approach
Simple ad-hoc HTTP calls (GET, POST, PUT, DELETE, PATCH)UTIL_HttpClient
Complex integrations with DTOs, validation, or orchestrationAPI_Outbound
Quick prototypes or one-off calls that still need loggingUTIL_HttpClient
Your own handlers with custom processing logicUTIL_HttpClient with useHandler()

Ad-hoc mode: direct calls with a Named Credential (or ApiCredential__mdt DeveloperName) and URL path:

apex
// Simple GET
HttpResponse response = UTIL_HttpClient.get('CRM', '/accounts/{id}')
	.pathParam('id', accountId)
	.send();

// POST with retry
HttpResponse response = UTIL_HttpClient.post('PaymentGateway', '/charges')
	.body(chargeRequest)
	.withRetry(3)
	.send();

// DELETE
HttpResponse response = UTIL_HttpClient.del('CRM', '/contacts/{id}')
	.pathParam('id', contactId)
	.send();

What a response tells you. Check the status code first, before you read the body: getting a response object back does not mean the remote system answered.

You seeIt meansWhat to do
Status code 0The call produced no response. Either it was refused before it ever left your org (a credential that could not be resolved, an open circuit breaker, a refusal from validation), or it did go out and nothing came back (a timeout, a transport failure)Read getStatus(): the status line carries the reason, when one was recorded. A call that got no answer is retried later only when the request is safe to repeat; see Failures and retries
Any other status codeThe call was answered, by the remote system or by a mockRead the body with getBody()
invoke() returns nullNo handler resolved for the callCheck for null before you read handler.result
  • send() always hands back an HttpResponse, never null, so you can call getStatusCode() and getBody() without a null check.
  • You do not need a try/catch around send(). Every failure the framework handles for a call still ends in a response from send(): a refused call, a transport failure, an exception in your handler, a call record that could not be saved, or a masking rule that blocked the call's attachments.
  • The only exception you cannot catch is a governor limit. It is the platform's own exception and cannot be caught by any Apex code.

invoke() gives you the same picture through the handler it returns:

apex
if (response.getStatusCode() == 0)
{
	// No response came back. response.getStatus() carries the reason, when one was recorded.
}

API_Outbound handler = UTIL_HttpClient.useHandler(API_SendEmail.class)
	.credential('PaymentGateway')
	.invoke();

if (handler != null && handler.result.hasFailed)
{
	// handler.result carries the structured outcome, including the recorded errors.
}

Delegation mode: route processing through your own handler via useHandler():

apex
API_Outbound handler = UTIL_HttpClient.useHandler(API_SendEmail.class)
	.credential('PaymentGateway')
	.withParameter(API_SendEmail.PARAM_RECIPIENT, email)
	.withTriggeringRecord(recordId)
	.invoke();

Settings you give on the call override the handler's ApiSetting__mdt defaults. A setting you leave out falls back to the handler's custom metadata (CMDT) value:

Builder methodOverrides
.credential(name)Named Credential
.path(urlPath)EndpointPath__c
.withRetry(n)MaxRetryCount__c
.withRetry(n, backoff)MaxRetryCount__c + RetryBackoffSeconds__c
.withCircuitBreaker()CircuitBreakerEnabled__c
.withCircuitBreaker(name)CircuitBreakerEnabled__c, and the call uses the breaker you name instead of the handler's own
.onFailure(LOG_FAILURE)LogIssues__c

For full API details, see the UTIL_HttpClient reference.

Where credentials belong ​

Give a request its credentials through the Named Credential you pass as the first argument.

For an API that wants its key in a header, use an External Credential, the platform's own store for a secret an admin enters once. Keep the key there, then either:

  • declare the header on the credential itself; or
  • reference it from the call as .header('X-Api-Key', '{!$Credential.MyExternalCredential.ApiKey}').

With Allow Formulas in HTTP Header switched on for that Named Credential, Salesforce swaps that reference for the real key as the request leaves your org. What that gives you:

  • the secret never enters your code or the call record;
  • a retry sends the same reference again and authenticates the way the first send did, as long as the user it runs as can still use the credential.

The user a retry runs as needs the credential too. A scheduled retry runs as the user the original call ran as, so give that user the permission set that grants access to the External Credential. Support users who run a failed call again by hand need other permissions: see Who needs which permission?

A credential you set by hand on a header is not kept. This applies to a header the framework recognises as carrying a credential (Authorization, X-Api-Key and the others listed under API Test Harness).

  • The first send still goes out exactly as you wrote it, but the call record stores [REDACTED] in its place.
  • A call that then fails is parked instead of retried. Its ApiIssue__c record says in plain words that the call set the header itself, so the value was not kept and a retry cannot send it.
  • The Retry action on that record stops the same call with the same message.

Move the key onto a Named Credential or an External Credential and the first send and every retry both work again.


Framework Orchestration Pattern ​

The framework always runs callouts before it saves any record, so you never hit the "uncommitted work pending" error. Salesforce refuses to make an HTTP callout once you have unsaved database changes in the same transaction. It throws "Callout from triggers with uncommitted work pending is not allowed".

API_Dispatcher keeps the two steps apart for you by always doing the work in a fixed order:

  1. All HTTP callouts run first (so there is never unsaved work pending when a callout happens)
  2. All database changes are saved afterwards, once the callouts have completed
  3. Errors are handled cleanly at each stage

What problem does this solve? ​

Every integration in Apex needs the same plumbing: build the request, send it, parse the response, log what happened, retry on failure, hide sensitive data, and make sure the callout runs before you save any records. Written by hand, it is repeated in every integration and drifts out of step.

KernDX writes that plumbing once. You extend a base class and write what is unique to your call (the URL, the body, what to do with the answer); the framework runs the rest. It works in both directions: calls Salesforce makes to other systems (outbound) and calls other systems make into Salesforce (inbound).

Use it for every callout your Apex makes and every endpoint you expose. KernDX expects them to go through this framework, because that is how each call gets its call record, its retries and its masking.

Mental model ​

Think of the framework as a shipping department for your integrations. You write the contents of the parcel (the request body and what to do with the reply). You decide what goes in the box; the department guarantees how it ships, the same way every time:

  • it stamps and addresses each parcel (endpoint, headers, credentials);
  • it keeps a copy of everything sent and received (the audit log);
  • it re-sends when delivery fails (retries);
  • it stops sending to an address that keeps bouncing (the circuit breaker);
  • it blacks out anything sensitive on the copy it files (data masking).

Use this when ​

  • The integration has to survive in production: failures must be logged and retried, not lost.
  • Sensitive data (cards, tokens, personal details) must be kept out of your logs automatically.
  • Several developers build integrations and you want them all to follow the same patterns.
  • An admin needs to call an API from a Flow, or turn an integration off during an incident, without writing or deploying code.
  • A callout has to run from a trigger, where the callout must happen before any record is saved.

Don't use this when ​

KernDX is opinionated here: every callout your Apex makes goes through this framework, a one-off in anonymous Apex too (that is one line with UTIL_HttpClient). Only work that needs no Apex at all stays outside it.

  • A Flow, outbound message, or Platform Event can send the outbound notification without code: stay with the built-in tool.
  • The API publishes an OpenAPI spec and you want admins to wire it into Flows with no Apex at all: use Salesforce External Services, which imports the spec. The framework does not read OpenAPI specs; with it, you write the DTOs yourself.

Building Outbound APIs ​

An outbound API is a call your Salesforce code makes to an external system: Salesforce sends the HTTP request out. You write only the parts unique to your integration; the framework handles the request, retries, logging, and saving any records afterward.

Step 1: Choose Your Base Class ​

Step 2: Override Virtual Methods ​

The base class already does most of the work, so you only override the methods where its default behaviour isn't what you need. For a simple call that can mean overriding nothing beyond the configuration. Each overridable method is explained in the Virtual Methods Reference section.

Minimal Implementation ​

This is the smallest outbound API you can write. It overrides only configure() to point at a response DTO (a small class that holds the fields you expect back and converts itself to and from JSON), so that the framework can turn the outgoing request into JSON and the incoming reply back into Apex for you.

apex
/**
 * @description Minimal outbound API implementation showing required overrides only.
 *
 * @author your.name@company.com
 *
 * @group Web Services
 *
 * @date January 2025
 */
public inherited sharing class API_MinimalExample extends API_Outbound
{
	/**
	 * @description Initializes the API handler with response DTO.
	 * The framework will auto-serialize requests and deserialize responses.
	 */
	public override void configure()
	{
		super.configure();
		responsePayload = new DTO_Response();
	}

	/**
	 * @description Data Transfer Object for API response.
	 */
	@JsonAccess(deserializable='always')
	public class DTO_Response extends DTO_JsonBase
	{
		public String result;

		/**
		 * @description Returns the type of this DTO for proper deserialization.
		 *
		 * @return The DTO_Response class type
		 */
		public override Type getObjectType()
		{
			return DTO_Response.class;
		}
	}
}

Complete Real-World Example: REST GET with Parameters ​

For a fully worked GET call, look at API_GetPwndPasswords in the framework source. It shows the common pieces in one place: encoding URL parameters, setting custom headers, and checking that required parameters were supplied before the call runs.

Complete Real-World Example: REST POST with DML ​

This example sends email through an external service and then records each successful send as a Task. It shows every common override together:

  • declaring which input parameters are required;
  • adding a tracking header;
  • validating and parsing the incoming JSON;
  • creating records after the call. The Task inserts happen in onSuccess(), which the framework runs after the callout completes, so the database work never blocks the callout.
apex
/**
 * @description Sends email via external service API and logs activity as Task.
 * Demonstrates POST requests, parameter validation, and database operations.
 *
 * @see API_SendMail_TEST
 *
 * @author your.name@company.com
 *
 * @group Communications
 *
 * @date January 2025
 */
public inherited sharing class API_SendMail extends API_Outbound
{
	/**
	 * @description The required parameter name for send mail request JSON.
	 */
	public static final String REQUIRED_PARAMETER_REQUEST_JSON = 'sendMailRequests';

	/**
	 * @description Initializes the API handler with request/response DTOs and mock.
	 */
	public override void configure()
	{
		super.configure();
		requestPayload = new DTO_Request();
		responsePayload = new DTO_Response();
		defaultMockBody = '{"results": [{"success": true}]}';
		requiresTriggeringRecord = false;
	}

	/**
	 * @description Specifies required request parameters for validation.
	 *
	 * @return Set containing required parameter names
	 */
	public override Set<String> getRequiredInputs()
	{
		Set<String> requiredParameters = super.getRequiredInputs();
		requiredParameters.add(REQUIRED_PARAMETER_REQUEST_JSON);
		return requiredParameters;
	}

	/**
	 * @description Adds custom correlation header for request tracking.
	 */
	public override void setHeaders()
	{
		super.setHeaders();
		request.setHeader('X-Correlation-Id', UTIL_Random.randomUUID());
	}

	/**
	 * @description Validates and deserializes the send mail request parameter.
	 *
	 * @return List of validation error messages
	 */
	public override List<String> getValidationErrors()
	{
		List<String> errors = new List<String>();
		DTO_Request dtoRequest = (DTO_Request)requestPayload;

		try
		{
			dtoRequest.dtoSendMailRequests =
				(List<DTO_SendMailRequest>)JSON.deserialize(
					inputs.get(REQUIRED_PARAMETER_REQUEST_JSON),
					List<DTO_SendMailRequest>.class
				);

			if(dtoRequest.dtoSendMailRequests == null || dtoRequest.dtoSendMailRequests.isEmpty())
			{
				errors.add('No send mail requests provided');
			}
		}
		catch(Exception error)
		{
			errors.add('Invalid JSON: ' + error.getMessage());
		}

		return errors;
	}

	/**
	 * @description Creates Task records for each successfully sent email.
	 * DML operations are committed after all callouts complete.
	 */
	public override void onSuccess()
	{
		super.onSuccess();

		DTO_Response dtoResponse = (DTO_Response)responsePayload;

		for(Integer i = 0; i < dtoResponse.results.size(); i++)
		{
			if(dtoResponse.results[i].success)
			{
				Task newTask = new Task
				(
					Subject = 'Email sent',
					Status = 'Completed',
					Type = 'Email'
				);
				doInsert(newTask);
			}
		}
	}

	/**
	 * @description Data Transfer Object for send mail request.
	 */
	@JsonAccess(serializable='always')
	private class DTO_Request extends DTO_JsonBase
	{
		private List<DTO_Mail> messages = new List<DTO_Mail>();
		private transient List<DTO_SendMailRequest> dtoSendMailRequests;

		/**
		 * @description Populates the mail messages from the request list.
		 *
		 * @param recordId The record that triggered this API call (unused in this implementation)
		 */
		public override void populate(Id recordId)
		{
			super.populate(recordId);

			for(DTO_SendMailRequest request : dtoSendMailRequests)
			{
				DTO_Mail mail = new DTO_Mail();
				mail.toAddress = request.toAddress;
				mail.subject = request.subject;
				mail.body = request.body;
				messages.add(mail);
			}
		}
	}

	/**
	 * @description Data Transfer Object for individual mail message.
	 */
	@JsonAccess(serializable='always')
	private class DTO_Mail
	{
		public String toAddress;
		public String subject;
		public String body;
	}

	/**
	 * @description Data Transfer Object for API response.
	 */
	@JsonAccess(deserializable='always')
	private class DTO_Response extends DTO_JsonBase
	{
		public List<DTO_SendMessageOutcome> results;

		/**
		 * @description Returns the type of this DTO for proper deserialization.
		 *
		 * @return The DTO_Response class type
		 */
		public override Type getObjectType()
		{
			return DTO_Response.class;
		}
	}

	/**
	 * @description Data Transfer Object for individual send outcome.
	 */
	public class DTO_SendMessageOutcome
	{
		public Boolean success;
		public List<String> errors;
	}

	/**
	 * @description Data Transfer Object for send mail request parameters.
	 */
	public class DTO_SendMailRequest
	{
		public String toAddress;
		public String subject;
		public String body;
	}

}

Step 3: Create ApiSetting__mdt Record ​

The last setup step is a configuration record that tells the framework how to run your class: which class, which endpoint, which stored credential, and how to behave on failure. Because these live in metadata, you can change the retry count or turn logging on or off without touching code.

Create a custom metadata record with these values:

FieldValue
LabelAPI Send Mail
ClassName__cAPI_SendMail
EndpointPath__c/api/v1/send
ApiCredential__c(Lookup to credential)
MaxRetryCount__c3
RetryBackoffSeconds__c30
LogIssues__ctrue
ResolveIssues__ctrue

Step 4: Execute Your API ​

In production code, run the class through UTIL_HttpClient: UTIL_HttpClient.useHandler(API_SendMail.class), one .withParameter(name, value) for each parameter, then .invoke(). The handler invoke() returns carries the outcome in result, so you can check whether the call succeeded and act on it. The Delegation mode sample shows the whole call.

In a test, you may build the call yourself and run it through the dispatcher, as the sample below does:

  1. Build a queue item describing the request, with TST_Factory.newOutboundApiCall.
  2. Hand it to the dispatcher (API_Dispatcher.execute), which runs the callout and any record saves in the right order.
  3. Read the result from the handler it returns, as in production.
apex
// Create queue item
ApiCall__c queueItem = TST_Factory.newOutboundApiCall(
	'API_SendMail',
	null,
	new Map<String, String>
	{
		'sendMailRequests' => JSON.serialize(new List<API_SendMail.DTO_SendMailRequest>
		{
			new API_SendMail.DTO_SendMailRequest()
		})
	}
);

// Execute synchronously
List<API_Base> handlers = API_Dispatcher.execute(
	new List<ApiCall__c>{ queueItem }
);

API_SendMail handler = (API_SendMail)handlers[0];

if(handler.result.isSuccess)
{
	// Process success - e.g., update UI, return result to caller
}

Building Inbound APIs ​

An inbound API is an endpoint you expose so that an outside system can call into Salesforce over HTTP. This is the receiving direction. A webhook, where another system pushes a request to a URL you expose, is an inbound API.

Inbound API Architecture ​

The framework splits each inbound REST endpoint into two classes, each with one job:

  1. REST Routing Class (REST_* prefix): carries the @RestResource annotation and decides which HTTP method (GET, POST, and so on) goes where. It does no business logic.
  2. API Implementation Class (API_* prefix): holds your business logic and extends API_Inbound.

Why splitting the two helps you:

  • Separation of Concerns: routing stays separate from logic, so each class is shorter and easier to read.
  • Multiple Operations: one REST endpoint can answer several HTTP methods, so related operations live at one URL.
  • Reusability: the same API implementation can be exposed at more than one endpoint, so you write the logic once.
  • Maintainability: changing the URL never touches your logic.
  • Flexibility: each HTTP method can hand off to a different API implementation.
  • Testing: you can test your logic on its own.

Do:

  • Use @RestResource only on REST routing classes
  • Delegate to API_Dispatcher.processInboundService()
  • Keep REST routing classes minimal (only routing, no business logic)

Don't:

  • Put @RestResource directly on API implementation classes
  • Manually instantiate API classes (e.g., new API_Echo().handleRequest())
  • Create separate REST classes for each HTTP method on the same endpoint

Minimal Inbound Example ​

Step 1: Create the REST Routing Class

apex
/**
 * @description REST Endpoint wrapper class for the inbound echo test service.
 * This class serves as a RESTFUL endpoint that listens for POST requests to the `/echo/*` URL mapping.
 *
 * @see API_Echo
 * @see API_Echo_TEST
 *
 * @author your.name@company.com
 *
 * @group Web Services
 *
 * @date January 2025
 */
@RestResource(urlMapping='/echo/*')
global inherited sharing class REST_Echo
{
	/**
	 * @description Handles the POST method for the echo service (inbound).
	 * Delegates processing to the API_Echo implementation class via the framework factory.
	 *
	 * @example
	 * POST /services/apexrest/echo
	 * Body: {"message": "Hello, Echo!"}
	 */
	@HttpPost
	global static void echo()
	{
		API_Dispatcher.processInboundService(API_Echo.class.getName());
	}
}

Key Points for REST Routing Classes:

  • Annotate the class with @RestResource and set its UrlMapping, which is the URL the endpoint answers on.
  • Each method must be global static and carry the matching HTTP method annotation (@HttpPost, @HttpGet, and so on).
  • Hand off to API_Dispatcher.processInboundService(), passing the name of the API class that holds the logic.
  • Use the global access modifier (@RestResource requires it).
  • Keep this class to routing only. No business logic belongs here.

Step 2: Create the API Implementation Class

apex
/**
 * @description An example Inbound API call that will echo exactly what was sent.
 * Contains the business logic for processing echo requests.
 *
 * @see REST_Echo
 * @see API_Echo_TEST
 *
 * @author your.name@company.com
 *
 * @group Web Services
 *
 * @date January 2025
 */
public inherited sharing class API_Echo extends API_Inbound
{
	@TestVisible
	private static final String ERROR_NO_BODY_RECEIVED = 'No request body received';

	/**
	 * @description Validates that a request body was provided.
	 *
	 * @return List of validation error messages
	 */
	public override List<String> getValidationErrors()
	{
		List<String> errors = new List<String>();

		if(String.isEmpty(requestBody))
		{
			errors.add(ERROR_NO_BODY_RECEIVED);
		}

		return errors;
	}

	/**
	 * @description Sets the response to echo back the request body.
	 */
	public override void updateCallResult()
	{
		super.updateCallResult();
		result.responseBody = requestBody;  // Echo back exactly what was sent
	}
}

Key Points for API Implementation Classes:

  • Extend API_Inbound (or your own base class that extends it).
  • Do NOT add the @RestResource annotation here. That belongs on the URL routing class.
  • Make the class global, so the framework can find it in your org with no extra setup. If you prefer public, register a Type Resolver (it tells the framework where to find your own classes; see Type Resolution).
  • Override the virtual methods to plug in your behaviour.
  • This is where all the business logic and data processing lives.

Advanced Example: Multiple Operations on One URL ​

A single URL often needs to do more than one thing: read a record and update it, for instance. This example shows how one REST routing class answers multiple HTTP methods, with each method handing off to a different API implementation class. So you keep one tidy endpoint instead of a separate URL per operation.

Step 1: Create the REST Routing Class

apex
/**
 * @description REST API endpoint for managing person profile details.
 * Supports GET (retrieve) and PATCH (update) operations on the same URL endpoint.
 *
 * @see API_PersonRetrieve
 * @see API_PersonUpdate
 *
 * @author your.name@company.com
 *
 * @group Person APIs
 *
 * @date January 2025
 */
@RestResource(urlMapping='/v1/identity/persons/*')
global inherited sharing class REST_Person
{
	/**
	 * @description Handles HTTP GET requests to retrieve person profile details.
	 * Extracts identityId from URL path and delegates to API_PersonRetrieve.
	 *
	 * @example
	 * GET /services/apexrest/v1/identity/persons/f47ac10b-58cc-4372-a567-0e02b2c3d479
	 *
	 * Response (200 OK):
	 * {
	 *   "identityId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
	 *   "firstName": "John",
	 *   "lastName": "Doe",
	 *   "email": "john.doe@company.com"
	 * }
	 */
	@HttpGet
	global static void getPerson()
	{
		API_Dispatcher.processInboundService(API_PersonRetrieve.class.getName());
	}

	/**
	 * @description Handles HTTP PATCH requests to update person profile details.
	 * Delegates to API_PersonUpdate for processing.
	 *
	 * @example
	 * PATCH /services/apexrest/v1/identity/persons/
	 * Body:
	 * {
	 *   "identityId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
	 *   "firstName": "John",
	 *   "lastName": "Smith"
	 * }
	 */
	@HttpPatch
	global static void editPerson()
	{
		API_Dispatcher.processInboundService(API_PersonUpdate.class.getName());
	}
}

Step 2: Create API Implementation for GET Operation

API_PersonRetrieve, API_PersonUpdate, SEL_Contact and the CMN_ExternalReference__c field are not in the package. They are illustrative code written in this guide; replace them with your own classes and fields.

apex
/**
 * @description Processes person profile retrieval.
 * Retrieves person details based on identityId provided in URL path.
 *
 * @see REST_Person
 * @see API_PersonRetrieve_TEST
 *
 * @author your.name@company.com
 *
 * @group Person APIs
 *
 * @date January 2025
 */
public inherited sharing class API_PersonRetrieve extends API_Inbound
{
	/**
	 * @description The Contact record found based on the provided identity ID.
	 */
	protected Contact foundPerson;

	/**
	 * @description Initializes the response DTO.
	 */
	public override void configure()
	{
		super.configure();
		responsePayload = new DTO_Response();
	}

	/**
	 * @description Validates the identity ID and retrieves person data.
	 *
	 * @return List of validation error messages
	 */
	public override List<String> getValidationErrors()
	{
		List<String> errors = new List<String>();
		String identityId = request.requestURI.substringAfterLast('/');

		if(String.isBlank(identityId))
		{
			errors.add('Identity Id not provided');
		}
		else
		{
			foundPerson = SEL_Contact.findByExternalReference(identityId);

			if(foundPerson == null)
			{
				errors.add('No person found with the provided details');
			}
			else
			{
				DTO_Response dtoResponse = (DTO_Response)responsePayload;
				dtoResponse.identityId = foundPerson.CMN_ExternalReference__c;
				dtoResponse.birthdate = foundPerson.Birthdate;
				dtoResponse.email = foundPerson.Email;
				dtoResponse.firstName = foundPerson.FirstName;
				dtoResponse.lastName = foundPerson.LastName;
				dtoResponse.mobile = foundPerson.MobilePhone;
			}
		}

		return errors;
	}

	/**
	 * @description Data Transfer Object for person response.
	 */
	@JsonAccess(serializable='always')
	public class DTO_Response extends DTO_JsonBase
	{
		public String identityId;
		public Date birthdate;
		public String email;
		public String firstName;
		public String lastName;
		public String mobile;
	}
}

Step 3: Create API Implementation for PATCH Operation

apex
/**
 * @description Processes person profile updates.
 * Updates person details and commits changes to database.
 *
 * @see REST_Person
 * @see API_PersonUpdate_TEST
 *
 * @author your.name@company.com
 *
 * @group Person APIs
 *
 * @date January 2025
 */
public inherited sharing class API_PersonUpdate extends API_Inbound
{
	/**
	 * @description The Contact record to be updated.
	 */
	protected Contact upsertContact;

	/**
	 * @description Initializes the request and response DTOs.
	 */
	public override void configure()
	{
		super.configure();
		requestPayload = new DTO_Request();
		responsePayload = new DTO_Response();
	}

	/**
	 * @description Validates the request and finds the Contact to update.
	 *
	 * @return List of validation error messages
	 */
	public override List<String> getValidationErrors()
	{
		List<String> errors = new List<String>();
		DTO_Request dtoRequest = (DTO_Request)requestPayload;

		if(String.isBlank(dtoRequest.identityId))
		{
			errors.add('Identity Id not provided');
		}
		else
		{
			upsertContact = SEL_Contact.findByExternalReference(dtoRequest.identityId);

			if(upsertContact == null)
			{
				errors.add('No Person found for the identityId provided');
			}
		}

		return errors;
	}

	/**
	 * @description Updates the Contact record with data from the request.
	 * API_Base inherits DML methods from DML_Transaction, so doUpdate is called directly.
	 */
	public override void onSuccess()
	{
		super.onSuccess();

		DTO_Request dtoRequest = (DTO_Request)requestPayload;

		upsertContact.FirstName = dtoRequest.firstName;
		upsertContact.LastName = dtoRequest.lastName;
		upsertContact.Email = dtoRequest.email;

		doUpdate(upsertContact);
	}

	/**
	 * @description Updates the response DTO with committed data.
	 * This method is called after database commit completes.
	 */
	public override void updateResponseDTO()
	{
		super.updateResponseDTO();

		DTO_Response dtoResponse = (DTO_Response)responsePayload;
		dtoResponse.message = 'Person updated successfully';
		dtoResponse.identityId = upsertContact.CMN_ExternalReference__c;
	}

	/**
	 * @description Data Transfer Object for person update request.
	 */
	@JsonAccess(deserializable='always')
	public class DTO_Request extends DTO_JsonBase
	{
		public String identityId;
		public String firstName;
		public String lastName;
		public String email;
	}

	/**
	 * @description Data Transfer Object for update response.
	 */
	@JsonAccess(serializable='always')
	public class DTO_Response extends DTO_JsonBase
	{
		public String message;
		public String identityId;
	}
}

Multi-method routing ​

When one URL responds to several HTTP verbs, each verb routes to its own inbound handler class (the REST_Person example above handles both GET and PATCH).

  1. Salesforce picks the right method for the incoming verb based on the @HttpGet/@HttpPost/@HttpPut/@HttpPatch/@HttpDelete annotation on each method of the REST_* routing class.
  2. Each annotated method then hands off to a different API_* handler by passing that handler's class name to processInboundService():
Custom Metadata RecordClassName__cRouting Method
ApiSetting.GetPersonAPI_PersonRetrieve@HttpGet getPerson()
ApiSetting.EditPersonAPI_PersonUpdate@HttpPatch editPerson()

You create one ApiSetting__mdt record per handler, and its ClassName__c field ties that configuration record to the handler class.

When a request arrives, Salesforce selects the routing method that matches the verb, and that method calls API_Dispatcher.processInboundService(API_PersonRetrieve.class.getName()) (or whichever handler applies). The dispatcher then runs the framework's pipeline for you: pre-validation, authorisation, and the onSuccess() step. So your handler only fills in what is unique to the request.

Naming Conventions for Inbound APIs ​

REST Routing Classes:

  • Pattern: REST_*
  • Examples:
    • REST_Echo - Simple routing class
    • REST_Person - Resource routing class
    • REST_Invoices - Domain-specific routing class

API Implementation Classes:

  • Pattern: API_* or [Domain]_API_[Operation][Resource]
  • Examples:
    • API_Echo - Simple implementation
    • API_PersonRetrieve - Operation + Resource
    • API_PersonUpdate - Operation + Resource
    • DOMAIN_API_CreateCase - Domain + Operation + Resource

When a request fails ​

When a request another system sends you fails, the caller gets an error status and decides what to do next. It can fail because your code throws, the data it refers to is missing, or the service is switched off.

Every request leaves an API call record. Each request your org receives leaves an API call (ApiCall__c), whether it worked or not. The call is kept even when your handler's changes are rolled back. It keeps the request:

  • the address with its query string, the method, the body and the parameters;
  • the Idempotency-Key when the caller sent one;
  • a fingerprint of the body (a SHA-256 hash, in Idempotency Key Body Hash).

A body too long for the call's Request field is kept whole in a file on the call. There is one exception: when no handler can be built for the request's service, the call keeps only the start of the body, as much as the Request field holds, with no file and no fingerprint.

An API issue, when you ask for one. Tick Log Issues on the service's API setting, and a failed request also leaves an API issue (ApiIssue__c): an Open record that a support user can review, run again or dismiss. With Log Issues off, nothing changes for the caller and no issue is written.

  • What the issue holds: a link to its call, the service name, the direction (Inbound) and the error messages.
  • What it does not hold: a copy of the request. The call keeps the request, and running the issue again reads it from there.

These failures write an issue:

  • your processRequest() or onSuccess() throws, or the save of your changes fails and is rolled back;
  • the request is refused before your code runs, because the service's setting is inactive, its required feature flag is off, its bypass feature flag is on, or all APIs, or all inbound APIs, are switched off;
  • your getValidationErrors() returns errors or throws;
  • your handler's handleError() override throws.

These outcomes write no issue, even with Log Issues on:

  • the request's body cannot be read (for example, JSON that does not parse), so the call ends Aborted with HTTP 500 before your handler runs;
  • no handler can be built for the service;
  • the request reused an Idempotency-Key with another body (HTTP 409);
  • the answer came from an earlier call with the same key or from a mock;
  • your handler answered an error status on purpose and the call ended Completed;
  • Safe Mode, which saves nothing at all.

The issue is written after the caller's answer is decided, so it never changes the HTTP status the caller receives.

Permanent failures. Throw UTIL_Exceptions.PermanentFailureException from processRequest(), onSuccess() or getValidationErrors() for a request that can never work, however often it is sent: an order for a product that no longer exists, for example.

  • The call is then ticked Permanent Failure, and Retry never runs it again (see Failures and retries).
  • Its subclass UTIL_Exceptions.RequestRefusedException does not tick the box: a call that fails with it stays open to Retry.
  • Errors that getValidationErrors() returns are not permanent: the request may work once the data it refers to is fixed.

The caller owns the retry. The framework does not run a failed incoming request again on its own. The system that sent it is expected to send it again, as most integration platforms do. To let the framework tie that retry to the failure:

  • the caller sends an Idempotency-Key header (a value the caller picks for one request, explained under Idempotency (Inbound APIs));
  • the service has Idempotency Enabled.

The framework links a retry to the earlier failure only when the caller sends the same Idempotency-Key and the service has Idempotency Enabled; without a key nothing is linked.

The key also belongs to the user who sent it: two requests are the same request only when the same user sent them to the same service with the same key. For a request that is the same:

  • A retry with the same body is linked. Its call's Previous Attempt points at the newest earlier call of that request that received the same body and did not complete. The earlier call lists it under Later Attempts.
  • A success closes the earlier issues. With Resolve Issues also ticked, a request answered with a status from 200 to 299 marks Resolved the open issues of every earlier failed attempt, whatever body each one carried.
    • A caller that corrects its body after a 400 and sends it again with the same key therefore closes the first issue.
    • A later request with the first body and that key still gets 409.
    • An error status your handler answers on purpose resolves nothing.
  • Failing again adds no issue. While an earlier attempt still has an open issue, a failed retry writes no new one, so a caller that retries ten times leaves one open issue, not ten.

One key, one user, one request.

  • A request sent by another user with the same key is a new request: it links nothing, resolves nothing and gets no stored answer.
  • Ask the owners of each calling system to send a fresh value, such as a UUID (a long random identifier), for every new request, and to reuse it only when they send that same request again from the same integration user.
  • The framework reads the newest 20 calls of one key, so a key reused more often than that has its oldest calls left out.

Two first requests that carry the same key and arrive at the same moment are both processed, because neither has finished when the other one checks.


Intra-Org API Calls ​

What is it for? ​

API_CallCurrentOrg is a base class for API calls back into the same Salesforce org. You extend it, and it works out the org URL and authenticates as the current user automatically, so you write only the call itself.

Sometimes the system you need to call is your own org. You might want to run several record changes in one Composite API request, read schema through the Tooling API, or hit a custom REST endpoint you built. Without it, every call means looking up your org's URL, fetching a session ID, and formatting the authorization header.

What you get ​

  • No hardcoded org URL. It works out your org's base URL at runtime via URL.getOrgDomainURL(), so you do not hardcode it or set up a Named Credential (a stored, reusable connection definition).
  • Runs as the current user. It authenticates with the current user's session ID, so the call runs with exactly the permissions that user has.
  • The auth header is built for you. It puts the Authorization header in the correct Bearer token format.
  • Everything an outbound call gets. You still get the logging, retries, mocking, and error handling that every outbound call gets.

When to Use ​

Use API_CallCurrentOrg when you need to:

  • Call Salesforce REST APIs from within the same org
  • Use the Composite API to perform multiple operations in a single call
  • Access Tooling API endpoints
  • Call custom REST endpoints within your org with user context

Basic Usage ​

apex
/**
 * @description Calls Salesforce Composite API to perform multiple DML operations in a single call.
 * Demonstrates intra-org API usage with automatic session management.
 *
 * @see API_CompositeExample_TEST
 *
 * @author your.name@company.com
 *
 * @group Web Services
 *
 * @date January 2025
 */
public inherited sharing class API_CompositeExample extends API_CallCurrentOrg
{
	/**
	 * @description Initializes the API handler with request and response DTOs.
	 */
	public override void configure()
	{
		super.configure();
		requestPayload = new DTO_Request();
		responsePayload = new DTO_Response();
		defaultMockBody = '{"compositeResponse": [{"httpStatusCode": 201, "referenceId": "ref1", "body": {"id": "001000000000001"}}]}';
		requiresTriggeringRecord = false;
	}

	/**
	 * @description Data Transfer Object for Composite API request.
	 */
	@JsonAccess(serializable='always')
	public class DTO_Request extends DTO_JsonBase
	{
		public Boolean allOrNone = true;
		public List<CompositeSubRequest> compositeRequest;
	}

	/**
	 * @description Data Transfer Object for individual composite sub-request.
	 */
	@JsonAccess(serializable='always')
	public class CompositeSubRequest
	{
		public String method;
		public String url;
		public String referenceId;
		public Map<String, Object> body;
	}

	/**
	 * @description Data Transfer Object for Composite API response.
	 */
	@JsonAccess(deserializable='always')
	public class DTO_Response extends DTO_JsonBase
	{
		public List<CompositeSubResponse> compositeResponse;

		/**
		 * @description Returns the type of this DTO for proper deserialization.
		 *
		 * @return The DTO_Response class type
		 */
		public override Type getObjectType()
		{
			return DTO_Response.class;
		}
	}

	/**
	 * @description Data Transfer Object for individual composite sub-response.
	 */
	@JsonAccess(deserializable='always')
	public class CompositeSubResponse
	{
		public Integer httpStatusCode;
		public String referenceId;
		public Map<String, Object> body;
	}

}

How It Works ​

You do not need to write any of this, but here is how the convenience is delivered: API_CallCurrentOrg overrides three methods so the URL is resolved at runtime and the call authenticates as the current user.

apex
// 1. configure() — sets baseUrl to the current org domain
global protected virtual override void configure()
{
	super.configure();
	baseUrl = Url.getOrgDomainUrl().toExternalForm();
}

// 2. getAuthorisationToken() — returns Bearer token with session ID
global protected virtual override String getAuthorisationToken()
{
	return HTTP_AUTH_TOKEN_BEARER + UTIL_System.getApiEnabledSessionId();
}

// 3. getWebServiceEndPoint() — combines org domain URL with endpoint path
global protected virtual override String getWebServiceEndPoint()
{
	String orgBaseUrl = Url.getOrgDomainUrl().toExternalForm();
	String endpointPath = setting?.EndpointPath__c;

	return orgBaseUrl + (String.isNotBlank(endpointPath) ? endpointPath : '');
}

How do I configure this? ​

In your ApiSetting__mdt record:

FieldValue
ClassName__cAPI_CompositeExample
EndpointPath__c/services/data/v68.0/composite
ApiCredential__c(Leave blank - session ID handles auth)

Note: You can leave the credential blank for intra-org calls. The session ID handles authentication, and the org base URL is resolved at runtime via URL.getOrgDomainURL(), so there is no Named Credential to set up.

No Setup step before the call works. A call back into your own org goes out as an outbound callout, but Salesforce allows a callout to your org's own domain (the address URL.getOrgDomainURL() returns) without a Remote Site Setting and without a Named Credential. There is nothing to register in Setup first.

Only works from a live user session. From a background job, every call is rejected with an HTTP 401 (Unauthorised).

  • Why: API_CallCurrentOrg signs each call with the current user's session ID, and that session ID exists only while a real user session is active.
  • Asynchronous Apex has none: a scheduled job, a queueable, a batch, a future method, and therefore any step running inside an async chain all run without a user session. The call then goes out with no usable session and your org rejects it, every time.
  • Instead: to call back into your own org from a background job, authenticate with a stored connection: extend API_Outbound with a Named Credential (a stored, reusable connection definition) or an ApiCredential__mdt record, rather than API_CallCurrentOrg.

Do not reach for retry to paper over that 401 inside a chain. withRetry cannot heal a session that was never going to exist: the call is deterministic, so every attempt returns the same 401.

  • The 401 comes back as an ordinary HTTP response, so the step records a failed result with no thrown exception attached.
  • Keep 401 out of your .retryOn(...) set, or leave withRetry off for this step, so the deterministic failure fails permanently instead of spending your retry budget on the same answer.
  • With withRetry off, the service's own retries take charge, and they do not re-send a 401: it is outside the default set (408, 425, 429, 500, 502, 503, 504), so it is retried only if the handler's getRetryableStatusCodes() adds it.

See Retrying a failed step and ApiStep: Web Service Integration in the Async Processing Guide; for the full background-delivery composition, see Calling an external system only after the transaction commits.


How do I use it in a managed package? ​

CRITICAL Requirements for Managed Package Usage ​

Installed as a managed package, your integrations need two things or they fail at runtime: the @JsonAccess annotation on every DTO, and type resolution so the framework can find your classes. Both are needed because your org runs the framework code from a separate namespace.

@JsonAccess Annotation (MANDATORY) ​

The @JsonAccess annotation lets the framework turn your classes into JSON; without it the conversion fails. Salesforce blocks one namespace from serializing another namespace's class unless you explicitly grant permission.

Your data-transfer classes (DTOs, the small classes that hold exactly the fields you send or receive and convert themselves to and from JSON) live in your namespace, but the framework that turns them into JSON lives in the package namespace.

Every DTO that extends a managed package class needs the @JsonAccess annotation:

apex
// ✅ CORRECT - @JsonAccess grants managed package permission to serialize/deserialize
@JsonAccess(serializable='always' deserializable='always')
public class DTO_Request extends DTO_JsonBase
{
	public String customerId;
	public String orderNumber;
}

// ❌ WRONG - Will fail at runtime with "Type cannot be serialized as it is not globally visible"
public class DTO_Request extends DTO_JsonBase
{
	public String customerId;
}

When to use each setting:

  • Serializable='always' - Required when the managed package calls serialize() on your DTO to turn it into JSON to send out (outbound requests)
  • Deserializable='always' - Required when the managed package calls deserialize() to read JSON back into your DTO (inbound responses)
  • Use both when data flows in and out, which is the most common case

Type Resolution (MANDATORY) ​

Type resolution tells the framework where to find your classes, and you only need to set it up once.

When the framework reads a JSON response back into a DTO, it has to find the right Apex class in your namespace to build. Across a namespace boundary it can't discover that class on its own, so set up type resolution in one of these three ways:

Option A: Make DTOs Global (simple but exposes classes)

apex
@JsonAccess(serializable='always' deserializable='always')
global class DTO_Request extends DTO_JsonBase
{
	public String data;
}

Option B: Implement getObjectType() in Every DTO (repetitive but explicit)

apex
@JsonAccess(serializable='always' deserializable='always')
public class DTO_Request extends DTO_JsonBase
{
	public String data;

	public override Type getObjectType()
	{
		return DTO_Request.class;
	}
}

Option C: Register Type Resolver (recommended: flexible and maintainable)

  1. Create resolver class:
apex
/**
 * @description Custom type resolver for subscriber org classes
 *
 * @see UTIL_TypeResolver
 */
global with sharing class CustomTypeResolver extends kern.UTIL_TypeResolver.BaseClassResolver
{
	/**
	 * @description Resolves a Type object from a class name
	 *
	 * @param className The name of the class to resolve
	 *
	 * @return Type The resolved Type object or null if not found
	 */
	public override Type resolveType(String className)
	{
		return getTypeForClassName(className) ?? (Type)nextResolver?.resolveType(className);
	}

	/**
	 * @description Resolves the Type for a given class name, handling namespaces and nested classes
	 *
	 * @param className The class name to resolve
	 *
	 * @return The resolved Type object, or null if not found
	 */
	private static Type getTypeForClassName(String className)
	{
		return String.isBlank(className) ? null : Type.forName(className);
	}
}
  1. Register in ClassTypeResolver__mdt:

    • Label: Custom Type Resolver
    • DeveloperName: CustomTypeResolver
    • ClassName__c: CustomTypeResolver
  2. That's it. With the resolver registered you no longer implement getObjectType() in any DTO.

If you skip type resolution, a response that needs to be read back into a DTO fails at runtime with this error:

text
System.JSONException: Type cannot be deserialized as it is not globally visible - DTO_Request

Complete Example with Namespace ​

apex
/**
 * @description Example outbound API demonstrating subscriber namespace usage.
 * Demonstrates proper namespace usage and coding standards.
 *
 * @author your.name@company.com
 *
 * @group Web Services
 *
 * @date January 2026
 */
public inherited sharing class MyAPI_SendEmail extends API_Outbound
{
	/**
	 * @description Initializes the API handler with required DTOs and mock class.
	 * This method is called by the framework before processing begins.
	 */
	public override void configure()
	{
		super.configure();

		requestPayload = new DTO_Request();
		responsePayload = new DTO_Response();
		defaultMockBody = '{"success": true, "messageId": "12345"}';
		requiresTriggeringRecord = false;
	}

	/**
	 * @description Sets HTTP headers required for the API call.
	 * Adds a custom correlation header for request tracking.
	 */
	public override void setHeaders()
	{
		super.setHeaders();
		request.setHeader('X-Correlation-Id', UTIL_Random.randomUUID());
	}

	/**
	 * @description Registers database changes to be committed after the API call succeeds.
	 * API_Base extends DML_Transaction, so doInsert/doUpdate/doDelete are inherited directly.
	 */
	public override void onSuccess()
	{
		super.onSuccess();

		Task newTask = new Task(Subject = 'Email sent', Status = 'Completed');
		doInsert(newTask);  // Inherited from DML_Transaction
	}

	/**
	 * @description Data Transfer Object for the API request payload.
	 */
	@JsonAccess(serializable='always')
	public class DTO_Request extends DTO_JsonBase
	{
		public String recipient;
		public String subject;
		public String body;
	}

	/**
	 * @description Data Transfer Object for the API response payload.
	 */
	@JsonAccess(deserializable='always')
	public class DTO_Response extends DTO_JsonBase
	{
		public Boolean success;
		public String messageId;

		/**
		 * @description Returns the type of this DTO for proper deserialization.
		 *
		 * @return The DTO_Response class type
		 */
		public override Type getObjectType()
		{
			return DTO_Response.class;
		}
	}

}

Calling Framework Methods ​

Because the framework lives in its own namespace, your org needs to know which package a class belongs to. You signal that by putting the package namespace in front of every framework class and utility you call, so the reference resolves to the installed package:

apex
// ❌ WRONG — missing namespace prefix
String abbreviated = UTIL_String.abbreviate(input, 100);
Id recordId = UTIL_SObject.validateId(stringId);

// ✅ CORRECT — use kern namespace prefix
String abbreviated = kern.UTIL_String.abbreviate(input, 100);
Id recordId = kern.UTIL_SObject.validateId(stringId);

API Dispatcher Usage ​

This is the form a test uses, from Step 4. Production code runs the class through UTIL_HttpClient.useHandler(...).invoke() (Delegation mode).

apex
// Create queue item
ApiCall__c queueItem = TST_Factory.newOutboundApiCall(
	'MyAPI_SendEmail',
	null,
	new Map<String, String>{ 'recipient' => 'test@example.com' }
);

// Execute via factory
List<API_Base> handlers = API_Dispatcher.execute(
	new List<ApiCall__c>{ queueItem }
);

// Access results
MyAPI_SendEmail handler = (MyAPI_SendEmail)handlers[0];

if(handler.result.isSuccess)
{
	// Process success - e.g., update UI, return result to caller
}

How do I call it from a Flow? ​

The framework gives Flow two ready-made actions for calling an API, so admins build integrations without writing Apex. A screen flow or a record-triggered flow reaches an external system the same way your Apex does, with the same logging and retry behind it.

  • Synchronous (an immediate response): the action waits for the answer.
  • Asynchronous (background processing): the action hands the work off to run in the background.

Understanding Synchronous vs Asynchronous Callouts ​

The choice comes down to one question: does the person running the flow need the answer right now, on screen?

  • Yes: use a synchronous call, and the flow waits.
  • No, the answer can arrive later (or no person is watching): use an asynchronous call, so nothing is held up.

The Comparison Matrix sets the two side by side: where each runs from, how long it may take (120 seconds for a synchronous call, the Salesforce limit), limits and retries.

When to Use Synchronous Callouts ​

Pick it when the API call is fast (typically < 5 seconds) or the flow needs the response to make decisions. It cannot be used in a before-save record-triggered flow.

Example Scenarios:

  • Data enrichment in a screen flow
  • Credit card verification during checkout
  • Real-time inventory check
  • Currency conversion for display

When to Use Asynchronous Callouts ​

Pick it when the API call might be slow or unreliable, or when you process large volumes of API calls (it can handle higher volumes via batch processing).

Example Scenarios:

  • Notifying external systems of record changes
  • Syncing data to external databases
  • Sending emails or notifications via third-party services
  • Background data enrichment

Synchronous Callouts from Screen Flows ​

Use Case: External API Call from Screen Flow ​

In the synchronous pattern the user waits a moment and sees the result: the user types something in, the flow calls an API, and the answer comes back before the user can move on.

Flow Type: Screen Flow Invocable Action: Invoke Callout SynchronouslyFramework Class: FLOW_CallApi

Flow Configuration:

  1. Create Screen - Collect user input

    Screen: Enter Details
    - Text Input: Title → {!title}
  2. Add Action Element - Invoke API Synchronously

    Action: Call External API
    Type: Invoke Callout Synchronously
    
    Inputs:
    - apiName: "API_PostExample"
    - recordId: {!recordId}
    - inputs: "foo={!title}"
    - inputDelimiter: "," (default)
    - extractPath: (optional - to extract specific JSON element)
    - idempotencyKey: (optional - your own key for spotting a repeat call)
    
    Store Outputs:
    - success → {!apiSuccess}
    - responseBody → {!apiResponse}
    - apiCallId → {!queueId}
    - extractedValue → {!extractedValue}
  3. Add Decision Element - Check API Result

    Decision: API Succeeded?
    Outcome 1: Success
      Condition: {!apiSuccess} Equals {!$GlobalConstant.True}
      → Go to next screen
    
    Outcome 2: Failed
      Condition: {!apiSuccess} Equals {!$GlobalConstant.False}
      → Show error screen
  4. Screen: Success - Display result

    Display Text:
    "API Response: {!apiResponse}"
  5. Screen: Error - Display error message

    Display Text:
    "API call failed: {!apiResponse}"

Input Parameters:

ParameterTypeRequiredDescriptionExample
apiNameString✅API class nameAPI_PostExample
recordIdString❌Record ID (if API needs record context){!recordId} or blank
inputsString❌Comma-separated name=value pairsfoo=Test Title
inputDelimiterString❌Delimiter for parameters (default: ,), or ;
extractPathString❌JSON path to extract specific elementtitle
idempotencyKeyString❌Your own key for spotting a repeat call. If you leave it blank, the framework makes one when repeat-call checks (idempotency) are on for the service (IdempotencyEnabled__c on its ApiSetting__mdt)ORDER-1001

Output Variables:

OutputTypeDescriptionExample Value
successBooleanWhether API call succeededtrue or false
responseBodyStringFull API response or error message{"body":"Some Random Body","id":101,"title":"Test Title","userId":9}
apiCallIdStringID of logged ApiCall__c recorda0X5g000000AbCD
extractedValueStringExtracted JSON element (if extractPath provided)Test Title

Asynchronous Callouts from Record-Triggered Flows ​

Use Case: Notify External System When Account is Created ​

In the asynchronous pattern you fire the call in the background and let the user's save finish straight away. The example tells an outside system every time a new Account is created; the save should not wait for that outside system to answer.

Flow Type: Record-Triggered Flow (After Save) Trigger: Account Created

How It Works:

You do not build the callout yourself. The framework ships with two built-in record-triggered flows on ApiCall__c that do the work for you:

FlowTriggerPurpose
ResetOutboundApiCallBefore SaveClears execution output fields (zero DML) when an ApiCall__c is set to Queued
InvokeOutboundApiCallAfter SaveInvokes FLOW_CallApiAsync to process the callout asynchronously

Your flow only needs to create the ApiCall__c record with Status__c = 'Queued'. The framework handles the rest, so your flow stays a single create step.

Why Asynchronous?

  • The InvokeOutboundApiCall flow calls FLOW_CallApiAsync, which enqueues a Queueable job (a background task Salesforce runs after the current transaction finishes)
  • Job size is configurable via AsynchronousJobSetting__mdt (default: 20, hard cap: 100 per the callout governor limit)
  • Keep the job size times your longest handler timeout under 120 seconds, the callout time one job has: a call the job cannot send in time still uses up one of its retries. Override getTimeout() in every handler to set its timeout. A handler that sets none waits up to 120 seconds, the whole callout time of a job.
  • Callout budget is monitored at runtime; remaining items are deferred if the limit is reached
  • Automatic retry if external system is temporarily unavailable
  • Better error handling and logging

Flow Configuration:

  1. Flow Properties

    Object: Account
    Trigger: A record is created
    Entry Conditions: All Conditions Are Met (Boolean) AND
      - Account Type Equals "Customer"
    Optimize the Flow For: Actions and Related Records
  2. Create Records Element - Build API Queue Item

    Create Records: Build API Queue Item
    How Many Records: One
    Object: ApiCall__c
    
    Set Field Values:
    - ServiceName__c: "API_NotifyAccountCreated"
    - TriggeringRecordId__c: {!$Record.Id}
    - Direction__c: "Outbound"
    - Status__c: "Queued"

That is the whole flow. You do not add an action element: the framework's InvokeOutboundApiCall flow triggers automatically when the ApiCall__c record is created with Status__c = 'Queued' and Direction__c = 'Outbound'. So an admin gets a background API call from a flow with one create step and no code.

Important Notes:

  • The flow completes immediately after creating the queue item
  • The API call executes asynchronously in the background via a Queueable job
  • Check ApiCall__c.Status__c to monitor progress
  • Framework automatically retries failed calls based on ApiSetting__mdt configuration
  • Cannot use the API response in the same flow (it happens later)

Comparison Matrix: Sync vs Async Callouts ​

AspectSynchronousAsynchronous
ExecutionBlocks until completeReturns immediately
Use FromScreen Flows, Manual InvocationRecord-Triggered Flows (after-save), Scheduled Flows
Response AvailableYes, immediatelyNo (logged to ApiCall__c)
Max Duration120 secondsNo practical limit (runs in Queueable/Batch)
Error HandlingMust handle in flowAutomatic retry via framework
User ExperienceUser waits for responseUser not blocked
Governor LimitsCounts against transaction limitsSeparate async limits
Best ForReal-time validation, Interactive formsBackground sync, Notifications, Data enrichment
Retry SupportManual onlyAutomatic via framework

Best Practices for Flow Integration ​

Always Check Success Flag ​

A callout can fail for reasons outside your control, so branch on the success flag rather than assuming the call worked.

text
Decision: API Call Successful?
Outcome 1: Success
  - Condition: {!apiSuccess} Equals true
  - Action: Proceed with success path
Outcome 2: Failure
  - Condition: {!apiSuccess} Equals false
  - Action: Display error message: {!apiResponse}

Provide User Feedback ​

Tell the user what is happening so a wait does not look like a freeze and a background job does not look like nothing happened.

For Synchronous Calls:

  • Show spinner/progress indicator during API call
  • Display success or error message based on response
  • Allow user to retry on failure

For Asynchronous Calls:

  • Inform user the action will complete in background
  • Provide reference number (apiCallId) for tracking
  • Set up email notifications for completion/errors

Handle Timeouts ​

An external API can be slow or unreachable, so add a fault path that shows a clear message instead of letting the flow error out.

text
Add Fault Path to Action Element:
- Store Error Message: {!$Flow.FaultMessage}
- Show Error Screen: "The API request timed out. Please try again."

Use Meaningful Parameter Names ​

Clear parameter names make the flow readable later and help whoever maintains the API class match values to fields.

text
✅ GOOD: inputs = "accountId={!recordId},accountName={!accountName}"
❌ BAD:  inputs = "id={!recordId},name={!accountName}"

Log Queue Item IDs ​

Store the apiCallId in a custom field for later tracking, so you can always trace a record back to the API call it triggered:

text
Update Record: Update Account
- WebserviceQueueId__c = {!apiCallId}

Testing Flow Callouts ​

You can write Apex tests for a flow callout the same way you test any flow, so a flow-driven integration is covered by your test suite rather than only checked by hand. The two examples below show one test for each pattern.

Test Synchronous Flow Callout ​

apex
@IsTest
private static void testSynchronousFlowCallout()
{
	Test.startTest();

	// The keys are input variables your flow declares and passes to the action's apiName and inputs.
	Map<String, Object> flowInputs = new Map<String, Object>
	{
		'apiName' => 'API_PostExample',
		'inputs' => 'foo=Test Title'
	};

	Flow.Interview flow = Flow.Interview.createInterview('YourFlowAPIName', flowInputs);
	flow.start();

	Boolean success = (Boolean)flow.getVariableValue('apiSuccess');
	String payload = (String)flow.getVariableValue('apiResponse');

	Test.stopTest();

	Assert.isTrue(success, 'API call should succeed');
	Assert.isNotNull(payload, 'Response payload should not be null');
}

Test Asynchronous Flow Callout ​

apex
@IsTest
private static void testAsynchronousFlowCallout()
{
	Account testAccount = (Account)TST_Builder.of(Account.SObjectType)
		.withOverride(Account.Name, 'Test Account')
		.build();

	Test.startTest();

	ApiCall__c queueItem = TST_Factory.newOutboundApiCall(
		'API_NotifyAccountCreated',
		testAccount.Id,
		new Map<String, String>()
	);
	FLOW_CallApiAsync.invokeApiCallAsynchronously(
		new List<ApiCall__c>{ queueItem }
	);

	Test.stopTest();

	SEL_ApiCall.assertServiceCompleted('API_NotifyAccountCreated');
}

What else can it do? ​

Some features work on the calls you make (outbound), some on the calls you receive (inbound), and some on both:

FeatureOutboundInbound
Automatic RetriesYesNo
Running a failed call again by handYes: sends the request againYes: replays the request in your org
Circuit Breaker PatternYesNo
Data MaskingYesYes
Mock Mode and API_MockFactoryYesYes
Disabling APIsYesYes
Performance MonitoringYesYes (callout time is outbound only)
Batched Outbound CallsYesNo
Safe ModeYesYes
API Test Harness (LWC and Tab)YesYes
Idempotency (Inbound APIs)Sends an Idempotency-Key header (Failures and retries)Yes

Automatic Retries ​

The retry strategies themselves (backoff shapes, jitter, and exception filters) are documented in depth in the Resilience - Guide. The web services framework applies retry to outbound calls via ApiSetting__mdt.

The framework can retry a failed outbound call for you on a schedule, so a temporary outage recovers on its own and the user's action does not fail with it. You turn this on by configuring ApiSetting__mdt; no extra code is needed.

How It Works:

When an API call fails, the framework:

  1. Decides, from where the call failed, whether sending it again could fix it (see Failures and retries); a failure a repeat cannot fix ends the call Failed at once
  2. Checks if MaxRetryCount__c is configured and not exceeded
  3. Calculates the next retry time using linear backoff (default strategy):
    • The delay is RetryBackoffSeconds__c multiplied by the number of retries already made. The first and second retries both wait the base delay.
    • Example: With RetryBackoffSeconds__c = 30, the retries wait 30, 30, then 60 seconds
    • The wait worked out from this value is never longer than 300 seconds. With RetryBackoffSeconds__c = 120, the retries wait 120, 120, 240, then 300 seconds, and every later retry also waits 300. A value above 300 has the same effect as 300. To wait longer, see Custom Retry Strategies.
  4. Sets NextRetry__c datetime field
  5. Sets Status__c to 'Retry'
  6. Increments Retries__c counter

A RetryBackoffSeconds__c of 0 schedules nothing, so the call ends Failed, except while the circuit breaker is open: then the retry waits for the breaker's cool-off.

Configuration:

In ApiSetting__mdt:

  • MaxRetryCount__c: Maximum number of retry attempts (e.g., 3)
  • RetryBackoffSeconds__c: Base backoff in seconds, multiplied as described above (e.g., 30). See the 300-second limit above.

Example Retry Schedule (with RetryBackoffSeconds__c = 30):

  • Original call fails at 10:00:00
  • First retry scheduled for 10:00:30 (30 seconds later)
  • If first retry fails, second retry scheduled for 10:01:00 (30 seconds later)
  • If second retry fails, third retry scheduled for 10:02:00 (60 seconds later)

Automatic Retry Processing:

Retry processing is fully automated out of the box: no custom scheduled jobs or platform events are needed. The framework ships with a built-in record-triggered flow (RetryOutboundApiCall) that processes retries. When an API call fails and the framework sets Status__c = 'Retry' with a NextRetry__c datetime, the flow:

  1. uses a time-based scheduled path to wait until the scheduled time;
  2. invokes FLOW_CallApiAsync, which sets Status__c to 'Retrying' to prevent re-triggering, then re-executes the callout.

A call that ends Failed is never picked up by the flow; the Retry action on its API issue is where you run it again (see Failures and retries).

What happens when Salesforce refuses to start a send? ​

Each outbound call is sent by a background job (a Queueable job). Salesforce can refuse to start that job, most often when your org has used up its 24-hour limit for asynchronous Apex jobs. Your save does not fail then: the call waits and is sent once Salesforce starts jobs again. This covers the jobs your save starts. Two kinds of send are not covered: see Which refused sends are only logged? below.

  • The save that queued the call succeeds.
  • Each call whose job did not start is saved at Retry, with a NextRetry__c time and the reason in ErrorMessages__c: "Salesforce refused to start the background send, so the request was not sent: the reason. It will be tried again at the time. The Next Retry field shows this time in your own time zone." The time is written in UTC in the ISO 8601 form, such as 2026-11-08T12:15:42.000Z, where the Z means UTC.
  • The RetryOutboundApiCall flow sends the call at that time, as for any other retry.
  • Retries__c does not change and no API issue is raised, because the request never left your org. A refusal does not use up the retries set by MaxRetryCount__c.
  • A call whose job did start is sent as usual. It is never sent twice.
  • The log gets one warning for each refused start. It says how many calls wait, when the first one is tried again and how many calls had already started. This warning is the only log entry for the refused start: no ERROR entry is written for it, because the calls are not lost.

The wait does not come from RetryBackoffSeconds__c. It is twice the call's last wait, never less than 15 minutes and never more than 240. For a new call, or a call whose last wait was short, each new refusal of the same call gives:

Refusal of the same callWait before the next try
First15 minutes
Second30 minutes
Third60 minutes
Fourth120 minutes
Fifth and later240 minutes

The limit counts the last 24 hours, so room always comes back. KernDX works out the last wait from the call itself (the time from its last save to its NextRetry__c), so if you edit a call while it waits, its next wait can be shorter, down to 15 minutes.

If your own code or flow calls the Invoke Callout Asynchronously action (FLOW_CallApiAsync.invokeApiCallAsynchronously), it gets the same behaviour: the method returns normally when a start is refused, and the calls wait at Retry. A call you pass at Retry is saved as Retrying before its send starts. A call you pass that is not saved yet (it has no Id) is saved as a new call at Retry, with the fields you gave it, so its request is still sent later.

The action's saves of the calls ignore record sharing, so they work whoever the flow runs as. The action trusts the records it is given: it changes them even when the running user cannot see or edit them.

  • If the save of a call to Retrying is refused anyway, for example by a validation rule, that call is not sent this time. It stays at Retry, and one warning log entry lists the Ids of the calls that were not sent. Where the Outbound Retry Watchdog is scheduled, it gives them a new NextRetry__c.
  • If that save is refused for every call at Retry, and the action got no other call, no job starts.
  • After a refused start, the warning counts only the calls whose save at Retry worked, and names the Ids of the calls whose save was refused. Each refused save has its own ERROR log entry.

With Salesforce's elastic limits (a beta setting) on, sends keep running past the standard limit, up to the elastic limit. See What happens to your background work at the 24-hour job limit? for the rest of your background work, and what KernDX recovers and what it only logs.

Which refused sends are only logged? ​

The calls wait at Retry only when Salesforce refuses a job while your save is starting it. In two kinds of send, a job can be refused later. KernDX then writes a log entry but does not change the calls:

  • A send split into a chain of jobs. Each job sends its share of the calls (20 by default), then starts the next job. This happens, for example, when more calls than one job sends are saved from inside a batch, Queueable or future job. If Salesforce refuses a later job of the chain, the calls of that job and of the jobs after it are not changed. One ERROR log entry lists them.
  • A send that runs as one batch job, for example when the transaction cannot start another Queueable job. At the limit the batch job fails before it sends any call. The calls are not changed, and one ERROR log entry gives Salesforce's reason.

What happens to those calls next depends on their status:

  • A call that was at Queued stays Queued. If you schedule the Outbound Retry Watchdog, it names the call in its warning about calls at Queued. Check the call and send it again yourself.
  • A call that was at Retry stays Retrying, because it was saved as Retrying before the send started. The watchdog later marks it Failed. When the service's API setting logs issues, it also raises an API issue marked External System May Have Acted.
  • A call you passed that was not saved yet (it has no Id) is lost: it is never saved, the watchdog cannot find it, and the ERROR log entry shows it only as null. Inside a batch, Queueable or future job, save your calls before you pass them.

Warning: such a Failed call was never sent, although its error text (and its API issue, when there is one) says the request may have been sent. Check the log for the ERROR entry of the refused job before you decide whether to send it again.

Turn on the Outbound Retry Watchdog ​

A retry can still be left behind. The background job that was sending a call again can be lost, or a call can sit at Retry after its time has passed with nothing to send it. The Outbound Retry Watchdog is a scheduled job that finds those calls and deals with each kind in one fixed way. It never sends a request on its own.

It does not run until you schedule it. Schedule it once, in one of two ways:

  • The declarative way, through the job runner: create a ScheduledJob__c record whose ClassName__c is SCHED_OutboundRetryWatchdog, running hourly (0 0 * * * ?); see Declarative Scheduling with ScheduledJob__c.
  • In Apex: System.schedule('Outbound Retry Watchdog', '0 0 * * * ?', new SCHED_OutboundRetryWatchdog()); does the same job.

Two optional attributes tune it:

AttributeWhat it setsDefault
StaleThresholdMinutesHow many minutes past its time a call must be before the watchdog acts on it60
BatchSizeHow many calls of each kind one run looks at, never more than 50; the rest wait for the next run50

What each run does:

Call it findsWhat the watchdog does
At Retry, with a NextRetry__c older than the thresholdGives the call a new NextRetry__c, twice its last wait (from 15 to 240 minutes), so the flow sends it again. Retries__c does not change. The log gets one warning
At Retrying, with a NextRetry__c older than the thresholdThe job that was sending it again has not finished. While a job that UTIL_AsynchronousJobLauncher.process() started after that time is still waiting or running, that job may still send it, so the call is left alone, for up to one day. A call does not record which job sends it, so most jobs that process() starts count, your own included. After that, or when no such job is live, the call is set to Failed, and ErrorMessages__c says the request may have been sent and its result could not be confirmed. If the service's API setting logs issues, an API issue is raised, marked External System May Have Acted. Check with the other system before you send the call again
At Queued, with no change for longer than the thresholdNothing is changed. The log gets one warning that names the calls, so you can check them and send them again if needed
At Retry, with no NextRetry__cLeft alone

Whose calls it changes. The watchdog reads and saves the calls of every user, whichever user the job runs as. You do not need to give that user access to other users' API calls. It logs a warning, or raises an API issue, only for a call whose change was saved. A call the save refused is not reported as moved or failed.

Before you first schedule it, look at the calls at Retry whose NextRetry__c is older than the threshold. The first runs give each of them a new NextRetry__c (at most BatchSize a run), however old the call is, and the flow then sends it. A call left at Retry weeks ago is sent then too. Change the status of any call you no longer want sent, for example to Failed, first.

After you first schedule it, the first run also looks at calls that have sat at Retrying since before you scheduled it, and can set them to Failed with the text above. Those requests may have been sent. Look at the API issues and the failed calls before you send any of them again.


Custom Retry Strategies ​

To give a handler its own retry behaviour, override createRetryStrategy() to return any UTIL_Retry.Strategy. By default, API_Outbound retries with a linear backoff built from RetryBackoffSeconds__c and MaxRetryCount__c.

That default is fine for most cases. A rate-limited service often needs the waits to grow faster between attempts, and to vary a little so callers don't all retry at the same instant:

apex
global inherited sharing class API_SendGridEmail extends API_Outbound
{
	global override UTIL_Retry.Strategy createRetryStrategy()
	{
		// Exponential backoff with jitter for a rate-limited API
		return UTIL_Retry.exponential()
			.withBaseBackoff(10)
			.withMaximumBackoff(300)
			.withMaxRetries(5)
			.withJitter(true);
	}
}

How to wait longer than 300 seconds. The wait the default strategy works out from the setting is never longer than 300 seconds, whatever RetryBackoffSeconds__c says. To wait the same longer time before every retry, override createRetryStrategy() and set the maximum wait to the same value as the base wait:

apex
public with sharing class API_SlowPartnerOrder extends API_Outbound
{
	public override UTIL_Retry.Strategy createRetryStrategy()
	{
		// Wait 600 seconds (10 minutes) before each of 6 retries: about an hour of cover
		return UTIL_Retry.linear()
			.withBaseBackoff(600)
			.withMaximumBackoff(600)
			.withMaxRetries(6);
	}
}
  • Why public override here: a global method compiles only inside a global class. Most handlers are public, so they declare the method public override. The API_SendGridEmail sample above is a global class, so it uses global override.
  • With jitter (.withJitter(true), which adds up to a quarter of the wait at random), give a maximum above the base, for example .withMaximumBackoff(750) for a base of 600. Jitter is added before the maximum is applied, so a maximum equal to the base removes the jitter. With the higher maximum, the third and later retries wait the maximum itself (750 seconds here).

When the framework asks your strategy.

  • createRetryStrategy() runs once for each failed call, after the response is in hand (or after the failure, when no response came back).
  • It runs on the same handler instance that ran prepareRequest(), parseResponse() and onSuccess(), so you can read response, result.statusCode and result.responseBody inside it.
  • The framework decides first, from where the call failed, whether sending it again could help at all (see Failures and retries). It asks your strategy only about a failure it may retry.

What the strategy sees. The context your strategy receives carries the retry count and, when the failure was an exception, that exception. A failure the external system answered with a status carries no exception, so an exception allowlist does not stop it and a denylist cannot match it: choose which statuses retry with getRetryableStatusCodes() instead.

How to say no. To refuse a retry, do one of these:

  • return a strategy whose shouldRetry answers false (UTIL_Retry.linear().withMaxRetries(0));
  • throw UTIL_Exceptions.PermanentFailureException (or its subclass RequestRefusedException for a refusal in a success body) from prepareRequest(), parseResponse(), onSuccess() or createRetryStrategy(). (Thrown from getValidationErrors() it ends the call Aborted, as every validation refusal does.)

Any other exception thrown while the framework decides ends the call Failed, with a warning in the log.

getRetryableStatusCodes() lists the HTTP statuses that may be retried. The default is 408, 425, 429, 500, 502, 503, 504.

Status, and what it meansRetried for
A 408, 425, 429 or 503 means the external system did not process the requestAny request
A 500, 502 or 504 can come after the external system did the workOnly a request that is safe to repeat: a GET, PUT or DELETE, or a request that carried an Idempotency-Key
A status you add is your own choiceAny request, whatever the method

Override the method to add a status your external system uses to mean "try later", or to remove one; an empty set retries no status.

getRetryableExceptionTypes() lists the exception types from your own code that may be retried.

  • It is empty by default: code that ran in your org and threw usually throws again on the next attempt, so the call ends Failed at once with one issue.
  • List a type when a failure of that type can pass on its own, such as a row lock.
  • A type is matched by its exact name, so list each concrete type you throw; a parent type such as Exception matches nothing.
A 200 whose body carries a business failure ​

Some systems answer 200 OK and put the refusal in the body. Throw UTIL_Exceptions.RequestRefusedException from parseResponse() so the call ends Failed and the framework never sends it again on its own, whatever your other retry settings say.

Use this exception, not the plain PermanentFailureException, for a refusal in a success body: the issue it leaves says the external system did not act, so a person can run the call again with Retry Selected on the API Issues list once you have fixed the cause.

Set the response DTO in configure() (after super.configure()), so super.parseResponse() reads the body into it:

apex
global inherited sharing class API_SendEmail extends API_Outbound
{
	global override void configure()
	{
		super.configure();
		responsePayload = new DTO_Response();
	}

	global override void parseResponse()
	{
		super.parseResponse();
		DTO_Response sendResult = (DTO_Response)responsePayload;
		if(sendResult.status == 'REJECTED')
		{
			throw new UTIL_Exceptions.RequestRefusedException('The provider rejected the message; fix the message and run the call again.');
		}
	}
}
A status failure the body proves permanent ​

Some systems answer a 503 for both "busy, try later" and "this account is closed". Read the body in createRetryStrategy() and refuse the retry only when it carries the permanent marker:

apex
global inherited sharing class API_SendEmail extends API_Outbound
{
	global override UTIL_Retry.Strategy createRetryStrategy()
	{
		if(result.responseBody?.contains('ACCOUNT_CLOSED') == true)
		{
			return UTIL_Retry.linear().withMaxRetries(0);
		}
		return super.createRetryStrategy();
	}
}

The full retry API is documented in the Resilience - Guide: exponential vs linear backoff, jitter, exception allowlists and denylists, and writing a custom UTIL_Retry.Strategy (for example, HTTP-status-aware backoff).

Failures and retries ​

Sending a request again only helps when the first attempt failed for a reason that can pass, and only when a second send cannot make the external system act twice. So before any retry setting is read, the framework looks at where the call failed:

Where the call failedWhat the framework does by defaultHow your handler changes it
Your own code threw before the request was sentEnds the call Failed at once: the same code throws againgetRetryableExceptionTypes() lets a listed type retry
The request went out and no answer came back (a timeout, a dropped connection)Retries when the request is safe to repeat: a GET, PUT or DELETE, or a request that carried an Idempotency-Key. Otherwise ends Failed at once, and the issue says the external system may have actedTurn on Idempotency Enabled, stamp a key with withIdempotencyKey(...), or list System.CalloutException in getRetryableExceptionTypes() (at your own risk on a POST or PATCH)
The external system answered with an error statusRetries 408, 425, 429, 500, 502, 503, 504; a 500, 502 or 504 only when the request is safe to repeat. Any other status ends Failed at oncegetRetryableStatusCodes() changes the set; it is the handler form of retryOn(...)
The external system answered with success, then your own code threwEnds Failed at once: the external system has already actedA type listed in getRetryableExceptionTypes() retries, but only when the request is safe to repeat
The circuit breaker was open, so the request was never sentTries again after the breaker's cool-off while retries remain; ends Aborted when the setting allows no retriesThe circuit breaker fields on the service's setting

A request is safe to repeat when the method is a GET, PUT or DELETE, or when the request carried an Idempotency-Key header. A POST or PATCH sent without a key that gets no answer, or gets a 500, 502 or 504, may already have been acted on, so the framework does not send it again on its own.

A callout the platform refused before it left your org (for example because unsaved work was pending in the transaction) reached nobody, so it is tried again while retries remain, whatever the method. Fix the cause in your code: the retry budget limits what it costs you.

Calls made with UTIL_HttpClient.

  • Retries. The immediate retries made inside send() never repeat a call that got no answer. The scheduled retry (which needs a wait time in withRetry(n, backoff)) does, when the request is safe to repeat.
  • withCircuitBreaker() uses the credential's own breaker, so every call on one credential shares one breaker.
  • withCircuitBreaker('PaymentGateway') uses a breaker you name instead. Calls that give the same name share one breaker whatever credential or handler they use. Calls that give different names keep separate breakers even on the same credential, so one failing endpoint does not stop calls to another.
  • Which breaker refused a call. A call refused by an open breaker says which breaker in its error line.
  • Named breakers and scheduled retries. The scheduled retry of a call built from a credential keeps the name. A call made through useHandler(...) uses the name when you make it, but its scheduled retry runs the handler on its own and uses the handler's own breaker.

A note on Idempotency Enabled. Stamp your own key with withIdempotencyKey(...) when two identical payloads are two separate requests.

The key the framework builds is a hash of the endpoint, the parameters and the body. Two calls with the same endpoint, parameters and body therefore share a key, so an external system that honours the header also treats a deliberate second send of the same payload as a repeat.

Running a failed call again by hand ​

Press Retry on an API issue to run its failed call again. A call that works marks the issue resolved.

The failed callWhat Retry does
A call your org madeSends the request to the external system again; the new call's Previous Attempt points at the call that failed
A call your org receivedReplays the request inside your org; its changes are kept when it works
  • Retry works on one issue at a time. Unless Resolve Issues is on (see below), the other open issues of the same outgoing request stay open. When several open issues record the same outgoing request, use Retry Selected on the API Issues list instead: it sends the request once and marks every issue of that request resolved.
  • An issue whose external system may have acted has the External System May Have Acted box ticked (ApiIssue__c.ExternalSystemMayHaveActed__c), and its error messages include a line that says why. Check with the external system first: pressing Retry sends the request again. The bulk retry skips these issues and leaves them open for a person to decide.

Replaying a request your org received. A replay is the recovery path for callers that never send a failed request again themselves. When the caller does retry (see When a request fails), leave Retry Issues off for that service, so a request is not run twice.

With it on:

  • Retry reads the request from the issue's call: the address, the method, the body (from the call's file when the body was too long for its field), the parameters and the Idempotency-Key.
  • It sends the request to the service the issue names, and the new call's Previous Attempt points at the call it replayed.

In these cases Retry refuses before anything runs, with a message, and the issue stays open:

Why the replay is refusedWhat the person sees
Retry Issues is off for the service"The request was not run again: Retry Issues is off in this service's API setting. Ask your administrator to turn it on if the callers of this service do not resend failed requests themselves."
The service is paused or switched off"This service is paused or switched off, so the request was not run again and the issue stays open. Ask your administrator to check the service's API setting and its feature flags."
The call is ticked Permanent Failure"This call failed in a way that running it again cannot fix, so it was not run again. The issue stays open."
The call no longer holds an exact copy of the request: masking changed the body, the body was cut and no file holds it, the address or the parameters fill their field and may have been cut, or the parameters cannot be read back"The stored request is not the one that was received: masking changed it, or it was too long to keep whole. It was not run again, and the issue stays open."
The call is gone, and the issue holds no copy of the request"The call this issue belongs to no longer exists and the issue holds no copy of the request, so there is nothing to run again. Dismiss the issue."

The body is checked against the fingerprint the call recorded when the request came in, so a replay never processes a masked or cut body as if it were real. An issue made by hand, with no call, is replayed from its own request fields, without that check.

A replay runs as the person who pressed Retry, but the request still belongs to the user who sent it. So when the service has Idempotency Enabled, its Idempotency-Key is checked as that user:

  • if the caller has already completed the request with that key, the replay gets the stored answer, runs nothing and resolves the issue;
  • once a replay works, the caller's own later retry with the same key gets the replay's answer too, so nothing runs twice.

A replay that fails writes no new issue: the issue it ran for stays the one open issue of the request.

A request too long for its field is replayed by a user who can see the call's files, such as an administrator.

  • A request whose body is too long for the call's Request field is kept whole only as a file on the call.
  • A user who holds only the Kern API Issue Resolver permission set cannot read that file, so the replay finds a cut body and refuses it as altered.

A handler that saves outside its unit of work is not safe to replay. A handler that saves records some other way may have saved part of its work before it failed, and a replay would save that part a second time.

A replay is safe only because your handler's changes are saved together, or rolled back together, through the inherited doInsert(), doUpdate() and doDelete().

Dismissing an issue ​

Dismiss closes an issue that will not be run again. Press Dismiss on an API issue to mark it Resolved without running anything.

  • Use it for a permanent failure, a request the call no longer holds, or a failure you dealt with another way.
  • It needs the Retry API Issue permission and works for both directions.
  • It frees the issue's call to be deleted or purged (see below).
Running many failed calls again at once ​

The calls run in one background job, so you can go on working. On the API Issues list, the screen tells you how many of the open issues you selected were queued.

Start it fromHow
The API Issues listSelect the issues and press Retry Selected
Your own flowAdd the Retry API Issues action (in the Api Callouts category) and pass it the issue ids
ApexCall kern.FLOW_RetryApiIssues.retryApiIssues, which takes one request holding apiIssueIds and answers with jobId, queuedCount, success and message

The job sends each distinct request once, even when several of the selected issues were logged for it, and marks every issue of that request resolved when the call succeeds. Some issues are left open instead:

  • an issue whose external system may have acted, and every other issue of the same request, even when you did not select the flagged issue;
  • an issue whose service is paused or does not allow retries: Retry Issues off, the setting inactive, its required feature flag off, its bypass feature flag on, or all APIs, or all APIs of the issue's direction, switched off;
  • an issue whose call is ticked Permanent Failure, and every other issue of the same request, even one logged on another call. Every open issue of the request counts, even one you did not select. The screen does not count any of them as queued;
  • an inbound issue that the button itself refuses, because it can tell without reading the request's body. The screen does not count these as queued. The button refuses when:
    • the issue has no call and no request of its own;
    • its call has an Idempotency-Key but no body fingerprint;
    • its call's address fills its field and may have been cut. A call with no key and no fingerprint whose address fills its field is not refused here when the issue holds a request of its own (its Request Path is filled in), because the job then runs the request the issue holds;
  • an inbound issue that the button counts as queued, but that the job refuses, because only the job reads the stored body. The job leaves the issue Open and writes a warning in the log. The job refuses when:
    • the body no longer matches its fingerprint;
    • the parameters were cut or cannot be read back;
    • the call has no key and no fingerprint, its body filled the Request field or was kept in a file, and the issue holds no request of its own;
  • an outbound issue whose own call, or a call for the same record, is still in progress or waiting to be sent, and every other issue of the same request. The job counts these in a warning in the log, so you can run them again when that call has finished.

In each batch of the job, the outbound calls are sent together first and the failed inbound requests are replayed after them. A replay saves data, and Salesforce does not allow a callout after unsaved data in the same transaction, so the replays must come last.

The job runs as the person who started it, so it sends nothing when that person no longer holds the Retry API Issue permission.

When Retry sends nothing ​

These rules hold for a call your org made and a call your org received alike, and the bulk retry follows them too:

  • Retry runs a call again only when the Retry Issues setting on its service is turned on.
  • Retry sends nothing while the service is paused or switched off (its setting inactive, its required feature flag off, its bypass feature flag on, or all APIs, or all APIs of the call's direction, switched off). The issue stays open, and the message says so.

Who may press it: see the Retry API Issue row in Who needs which permission?. The Kern API Issue Resolver permission set grants it to support users without the rest of the administrator's access.

Retry never runs a permanent failure again. Retry, Retry Selected and the Retry API Issues flow action all refuse a call ticked Permanent Failure.

  • What the box means. The call failed in a way that sending it again cannot fix: your code threw UTIL_Exceptions.PermanentFailureException.
  • The one exception. A UTIL_Exceptions.RequestRefusedException does not tick the box, so a refused call stays open to Retry (see A 200 whose body carries a business failure).
  • How the issue closes. It stays open until it is dismissed, or until a later success for the same request resolves it when Resolve Issues is on (see Automatic resolve).
  • Overriding it on purpose. For a call your org made, an administrator can still run it again: setting the call's Status back to Queued sends it again, and that is the deliberate way to override the marker.

Dead letters. Dead Lettered shows whether an outgoing call's automatic retries are used up, or that an administrator ticked Manual Dead Letter to give up on it. It does not decide whether Retry runs a call; Permanent Failure does.

  • There is no Recover action, whatever the help text of those two fields says in an org that upgraded from an earlier version.
  • To run an outgoing call again, untick Manual Dead Letter and set Status to Queued.
  • Setting Queued on an incoming call runs nothing.
Who needs which permission? ​
PermissionWho needs itWhat it allowsRead more
Kern Administrator permission setAdministratorsSees, edits and deletes every API issue and every API call. Grants the Retry API Issue and Delete API Records permissionsWho can see and change an API issue
Kern API Issue Resolver permission setSupport users, who run a failed call again by hand from its API issueGrants the Retry API Issue permission and access to the Retry action; read access to every API issue and every API call (View All Records); the API Issues tab and the Kern app. It grants no edit or delete accessRunning a failed call again by hand
Retry API Issue permissionAnyone who presses Retry, the resolve action, Dismiss or the bulk retryRunning a failed call again, or closing its issue. Both permission sets above grant itWhen Retry sends nothing
Delete API Records permissionAnyone who deletes API calls or API issues, and the user a scheduled purge runs asTurns the BypassApiRecordDeleteGuard flag on for the holder. The Kern Administrator set grants itWho can delete an API call or an API issue
Access to the External CredentialThe user the original call ran as: a scheduled retry runs as this same userA retry authenticates the way the first send didWhere credentials belong
View All Records on API issues and API callsAnyone who must see records other users madeBoth objects are private to their owner otherwise. Both Kern permission sets include itHow do I find the calls made for one record?
Who can see and change an API issue ​

API issues are private records. A person sees an issue only when they:

  • own it (the issue belongs to the user whose transaction made the failed call);
  • sit above the owner in the role hierarchy;
  • or hold View All Records on API issues.

Both Kern permission sets that deal with issues include View All Records, so you need no sharing rule or group. What each set may see and change is in Who needs which permission?. Two rules the table does not show:

  • Retry, the resolve action, Dismiss and Retry Selected mark an issue resolved for the resolver, whoever owns the issue. They do this only after checking that the person holds the Retry API Issue permission.
  • If you hold that permission through another permission set, without View All Records on API issues, Retry and the resolve action on an issue you cannot see send nothing and tell you so, and suggest you ask your administrator for the Kern API Issue Resolver set.

The sharing default is a setting your org owns, and an upgrade never changes it.

OrgSharing default for API Issue
A new installPrivate
An upgraded orgThe default it had, often Public Read/Write, until you change it; the View All Records access of the resolver set arrives with the upgrade either way

To check yours, open Sharing Settings and find API Issue under Organization-Wide Defaults. To make it Private, edit the default and set API Issue to Private. Your resolvers and administrators keep sight of every issue through their permission sets.

Who can delete an API call or an API issue ​

One feature flag, BypassApiRecordDeleteGuard, decides who may delete API calls and API issues, from a record page, a flow, your own Apex and the scheduled purge alike. These records are the history of every call to and from other systems, and an issue is the record that a call failed.

  • Who the flag is on for. A built-in rule turns it on for every person who holds the Delete API Records permission; the Kern Administrator permission set grants it.
  • Anyone else who tries, including a resolver, gets a message that says so, and nothing is deleted.
  • The scheduled purge. A scheduled purge of old API calls or API issues must run as a person the flag is on for, for example an administrator with the Kern Administrator set. So schedule it as that person: a purge scheduled by anyone else deletes nothing and writes one warning with the same message to the log.
  • Trigger bypass. The check runs in the API Call and API Issue triggers, so Apex that turns those triggers off with TRG_Base.bypass(...) also turns the check off, until that code clears the bypass or the transaction ends.

To let more people delete, or to see what happens when the flag record is deactivated, read Who can see the framework's own records? in the Security Guide.

A call with an open issue is kept until the issue is closed. No one can delete an API call that has an Open API issue: not a holder of Delete API Records, not a System Administrator, and not the purge.

The reason: an open issue is a failure nobody has dealt with yet, and its call holds the request that Retry runs again.

  • What the person is told: "This API call has an open API issue. Resolve or dismiss the issue first, then delete the call."
  • A delete of many calls that allows some to fail still deletes the other calls.
  • Once the issue is resolved or dismissed, the call can be deleted or purged.
  • When an earlier call is deleted or purged, the Previous Attempt of a later call that pointed at it is cleared.
  • Trigger bypass. This check runs in the API Call trigger too, so the same TRG_Base.bypass(...) turns it off.

The purge of API calls reads as the user who runs it:

  • When that user can read every open API issue, the purge leaves the calls with an open issue out of what it deletes. The Kern Administrator permission set gives this access.
  • When the user cannot see the open issue of a call, the purge still tries to delete it. The check above refuses that call, one call at a time, and each refusal is logged.
  • When the user cannot read API issues at all, the purge of API calls does not start, and one warning in the log says so.

A call left out is purged by a later run, once its issue is resolved or dismissed.

Automatic resolve ​

With Resolve Issues on, a later success resolves earlier open issues for the same request:

DirectionWhat the later success resolves
A call your org makesEvery user's open issue for that request, whoever made the call that failed
A request your org receivesOnly the issues of earlier requests the same user sent with that key; the resolve needs Idempotency Enabled and a key (see When a request fails)

Circuit Breaker Pattern ​

A circuit breaker stops calling an external system that keeps failing: after a system fails repeatedly, the framework stops calling it for a short cool-off period, then quietly tries again to see if it has recovered. Later calls fail fast instead of piling up timeouts that slow your users down.

You switch this protection on for each service with Circuit Breaker Enabled (CircuitBreakerEnabled__c) on its API setting; it is off until you do.

The breaker has three states it moves between on its own: normal operation (CLOSED), tripped and refusing calls during the cool-off (OPEN), and cautiously testing whether the system is back (HALF_OPEN).

The circuit breaker concept is covered in depth in the Resilience - Guide: the three states and their transitions, the execute() helpers, metrics, and Platform Cache persistence. The web services framework wires it onto outbound calls via ApiSetting__mdt.


How It Works in the Framework ​

Once it sees a run of failures, the framework starts rejecting calls to the failing service quickly, so that service can no longer drag down every other call.

Turning it on: The breaker runs only for a service whose ApiSetting__mdt record has CircuitBreakerEnabled__c checked. The field is unchecked by default, so a service without it is never refused for an open circuit.

Configuration via ApiSetting__mdt:

FieldDescriptionExample
CircuitBreakerEnabled__cTurns the breaker on for this service (unchecked by default)true
CircuitBreakerFailureThreshold__cConsecutive failures before opening circuit5
CircuitBreakerTimeout__cSeconds to keep circuit open before testing recovery60
CircuitBreakerSuccessThreshold__cConsecutive successes in half-open state to close circuit2

Example Configuration:

text
DeveloperName: SendGrid_Email_API
ClassName__c: API_SendGridEmail
CircuitBreakerEnabled__c: true
CircuitBreakerFailureThreshold__c: 5
CircuitBreakerTimeout__c: 60
CircuitBreakerSuccessThreshold__c: 2

Behavior:

  1. After 5 consecutive failures, circuit opens
  2. For the next 60 seconds, every call is refused without being sent, and its record says the circuit breaker is open. A call whose setting allows retries is tried again after the cool-off while it has retries left; a call whose setting allows none ends Aborted
  3. After 60 seconds, circuit enters half-open state
  4. Test requests are allowed to verify recovery
  5. After 2 consecutive successes, circuit closes (normal operation)
  6. If a test fails → circuit re-opens for another 60 seconds

State Transitions Example ​

Scenario: External email API experiencing issues

text
Time      Event                           Circuit State    Action
--------  ------------------------------  ---------------  ----------------------------------
10:00:00  Call fails (timeout)            CLOSED           Failure count: 1
10:01:00  Call fails (503 error)          CLOSED           Failure count: 2
10:02:00  Call fails (timeout)            CLOSED           Failure count: 3
10:03:00  Call fails (503 error)          CLOSED           Failure count: 4
10:04:00  Call fails (timeout)            CLOSED → OPEN    Failure count: 5 (threshold reached)
10:04:20  Call attempted                  OPEN             Refused, not sent (the open-circuit line is recorded)
10:04:40  Call attempted                  OPEN             Immediately rejected
10:04:50  Call attempted                  OPEN             Immediately rejected
...
10:05:01  Call attempted                  OPEN → HALF_OPEN Timeout expired (more than 60 s), allow test requests
10:05:01  Test call 1 succeeds            HALF_OPEN        Test 1/2 passed
10:05:10  Test call 2 succeeds            HALF_OPEN → CLOSED  Test 2/2 passed, circuit closes
10:05:20  Call succeeds                   CLOSED           Normal operation resumed

Circuit State Persistence ​

Because the breaker is shared org-wide rather than reset for each request, one user's run of failures protects everyone else right away, instead of each transaction having to discover the outage on its own.

Circuit state is persisted in Platform Cache (org-wide), ensuring:

  • State maintained across transaction boundaries
  • All users see the same circuit state
  • Protection applies org-wide (not per-user)

Example:

apex
// User A's call at 10:04 is the 5th failure in a row, so the circuit opens
API_Outbound first = UTIL_HttpClient.useHandler(API_SendGridEmail.class).invoke();

// User B's call at 10:05 (different transaction, different user) reads the open state from the cache
API_Outbound second = UTIL_HttpClient.useHandler(API_SendGridEmail.class).invoke();
// Nothing was sent: second.result.errors holds
// "The circuit breaker for API_SendGridEmail is open after repeated failures, so the request was not sent."

Default Behavior (No Configuration) ​

Once CircuitBreakerEnabled__c is checked, you don't have to fill in the other fields: if you leave them blank, the framework falls back to safe starting values.

If CircuitBreakerEnabled__c is checked and the other circuit breaker fields are not configured in ApiSetting__mdt:

  • Default Threshold: 5 consecutive failures
  • Default Timeout: 60 seconds
  • Default Success Threshold: 2 consecutive successes in the half-open state
  • Default Half-Open Requests: 3

Without CircuitBreakerEnabled__c, the service has no circuit breaker at all.


Best Practices ​

Tune the breaker to match how critical each integration is and how fast it tends to recover: the right settings depend on the service you're calling.

1. Choose Appropriate Thresholds by Service Type

Service TypeThresholdTimeoutRationale
Critical Payment APIs2-3300s (5 min)Low tolerance, long recovery
Email/Notification5-1060s (1 min)Higher tolerance, quick retry
Internal Salesforce3-530sFast recovery expected
Rate-Limited APIs560sMatch rate limit window

2. Combine Circuit Breakers with Retry Strategies

Circuit breakers and retry strategies work together:

  • Retry Strategy: Handles failures a repeat can fix (1-3 attempts for network blips; see Failures and retries for which failures those are)
  • Circuit Breaker: Handles sustained failures (service is down)
apex
global inherited sharing class API_SendGridEmail extends API_Outbound
{
	// Retry handles a timeout on a call that is safe to repeat (GET, PUT, DELETE, or one that carries an Idempotency-Key)
	// and a 408, 425, 429, 500, 502, 503 or 504 answer
	global override UTIL_Retry.Strategy createRetryStrategy()
	{
		return UTIL_Retry.exponential()
			.withMaxRetries(3)
			.withBaseBackoff(10);
	}

	// Circuit breaker handles sustained failures (service outage)
	// Configuration loaded from ApiSetting__mdt automatically
}

Request Flow:

  1. Circuit breaker checks state (CLOSED = proceed, OPEN = refuse the call without sending it; with retries left, the call is tried again after the cool-off)
  2. If CLOSED, retry strategy attempts call (up to 3 times with backoff)
  3. If all retries fail, circuit breaker increments failure count
  4. When threshold reached, circuit opens

3. Monitor Circuit State

Check ApiCall__c for calls the open circuit refused:

  • a refused call was never sent, so it has no status code;
  • its ErrorMessages__c holds the line "The circuit breaker for service name is open after repeated failures, so the request was not sent."

ErrorMessages__c is a long text field, which SOQL cannot filter, so select the day's unsent calls and read that line in the results. Run it in the Developer Console Query Editor; it is a query you read, not code for a class:

soql
SELECT Id, ServiceName__c, Status__c, ErrorMessages__c, CreatedDate
FROM ApiCall__c
WHERE StatusCode__c = null
  AND Status__c IN ('Aborted', 'Retry', 'Failed')
  AND CreatedDate = TODAY
ORDER BY CreatedDate DESC

The query also returns calls refused before the send for another reason (a missing setting, a missing parameter), which is why you read the line. The line comes from the OutboundCall_CircuitOpen custom label, so if your org translates or overrides that label, look for your wording.

4. Environment-Specific Configuration

Use different thresholds per environment:

Development/Sandbox (more tolerant for testing):

text
CircuitBreakerFailureThreshold__c: 10
CircuitBreakerTimeout__c: 30

Production (stricter for reliability):

text
CircuitBreakerFailureThreshold__c: 3
CircuitBreakerTimeout__c: 300

5. Handle an Open Circuit Gracefully

When the circuit is open, the framework does not send the call and records the open-circuit line in ErrorMessages__c. A call whose setting allows retries is scheduled again after the cool-off (Status__c = 'Retry') and ends Failed once its retries are used up; a call whose setting allows no retries ends Aborted. Implement fallback logic:

apex
// In your calling code: the call runs now, so its result is in hand when invoke() returns
API_Outbound handler = UTIL_HttpClient.useHandler(API_SendGridEmail.class)
	.withTriggeringRecord(emailId)
	.invoke();

Boolean isCircuitOpen = handler != null
		&& !handler.result.isSuccess
		&& String.join(handler.result.errors, '\n').contains('is open after repeated failures');

if(isCircuitOpen)
{
	// Circuit is open - use alternative approach
	// Option 1: Queue for later retry
	// Option 2: Use backup email service
	// Option 3: Store in offline queue
}

Advanced: Custom Circuit Breaker Configuration ​

Circuit breaker behaviour is configured per service via ApiSetting__mdt. For standalone use outside the web services framework, use the UTIL_CircuitBreaker API directly:

apex
// Standalone circuit breaker with custom thresholds
UTIL_CircuitBreaker.Breaker breaker = UTIL_CircuitBreaker.monitor('MyExternalService')
	.withFailureThreshold(10)       // More tolerant
	.withTimeout(600)                // Longer recovery (10 minutes)
	.withHalfOpenMaxAttempts(5);     // More confident recovery test

breaker.execute(new MyProtectedAction());

When to use standalone circuit breakers:

  • Custom non-API callout scenarios
  • Programmatic circuit control based on runtime conditions
  • Protecting non-HTTP operations (e.g., platform event publishing)

Troubleshooting ​

When the breaker isn't behaving the way you expect, the symptom usually points to one setting to adjust.

ProblemSolution
Circuit opens too frequentlyIncrease CircuitBreakerFailureThreshold__c (e.g., from 3 to 5 or 10)
Circuit stays open too longDecrease CircuitBreakerTimeout__c (e.g., from 300s to 60s)
Circuit closes prematurely after recoveryIncrease CircuitBreakerSuccessThreshold__c (e.g., from 1 to 3) to require more successful tests

Problem: Calls refused with "The circuit breaker for service name is open after repeated failures, so the request was not sent."

Cause: Service is genuinely down or experiencing issues

Solution:

  1. Check external service status
  2. Wait for timeout period to expire
  3. Circuit will automatically test recovery
  4. If needed, manually clear circuit state (see Utilities guide)

Data Masking ​

Data masking redacts sensitive values (a password, a token, a card number) before the log row of an API call is saved. Every API call is logged, so without it, secrets and personal data would sit in ApiCall__c and ApiIssue__c where anyone with read access could see them.

It uses the shared data masking framework. The payload fields (Request__c, Response__c, URL__c, RequestParameters__c, ErrorMessages__c) are redacted by the record's trigger, before insert and before update, so the values are masked before the row is saved.

Know what each kind of rule can reach on a stored call:

  • Key rules (JsonKey) read Request__c and Response__c as JSON, so they find a secret key inside nested objects there too.
  • In RequestParameters__c, the request body and the query parameters are stored as text inside the JSON. A key rule does not look inside JSON that is stored as text, so only the rules that search the text itself (Regex, CreditCard, ExactMatch) reach the body and the query parameters there.
  • The same copies are kept on the API issue (ApiIssue__c) when a call fails, so the same limits apply to it.

Keep secrets such as tokens and passwords in a Named Credential or an External Credential, never in the request body or the query parameters. The stored call then never holds them.

Default coverage out of the box (no admin work required for these):

  • MaskSecretKeys redacts JSON keys named password, token, apiKey, authorization, bearer, client_secret, private_key, access_token, refresh_token (and common variants).
  • MaskPaymentCard redacts 13–19 digit sequences that pass the Luhn checksum (all major card brands; spaces or hyphens allowed).
  • MaskJwt redacts JSON Web Tokens (a token that starts with eyJ and has three dot-separated parts) as [JWT_REDACTED].

Example: activate US-SSN masking on API payloads

Add a MaskingTarget__mdt wiring the shipped-but-inactive MaskSsn rule onto ApiCall__c. First flip MaskingRule.MaskSsn.IsActive__c = true, then create the target:

FieldValue
Rule__cMaskSsn
SObjectType__cApiCall__c
Field__cblank (wildcard across every text field, unique keys and external ids excepted)
IsActive__ctrue

Example: scope a rule to one service

Use CallerClass__c on a MaskingTarget__mdt when one rule (e.g., a credit-card format your processor uses) should apply only to one service's calls and not to unrelated callouts.

  • In CallerClass__c, enter the handler class that the service's API setting names, spelled the same way.
  • The target then masks that service's ApiCall__c and ApiIssue__c records and no others.
  • On any other object the target never fires (see the Data Masking Guide's Caller-Class Scoping).

How it works: only the logged copy is redacted; the actual HTTP request/response going over the wire is unaffected. The framework:

  1. reads the populated text fields of the record;
  2. caches the resolved rule-to-field plan for (SObjectType, callerClassName) once per transaction;
  3. applies each rule in rule-order, with JSON-key rules batched into a single deserialize/serialize pass.

Mock Mode and API_MockFactory ​

Mock mode stands in a fake response, so your integration logic runs without touching the live external system. You can't make real network calls from a unit test, and you often don't want to in a sandbox or demo either. The framework checks three places for a mock, in order, and uses the first one it finds:

  1. Memory mocks: API_MockFactory.forService() / API_MockFactory.registerErrorMock() (highest priority)
  2. Metadata mocks: ApiMock__mdt custom metadata records
  3. defaultMockBody: JSON string set on the handler class in configure()

defaultMockBody (Handler-Level Mocking) ​

The simplest option is to put a canned response right on the handler, so every test of that handler gets it automatically with no per-test setup. Set defaultMockBody in configure():

apex
public override void configure()
{
	super.configure();
	requestPayload = new DTO_Request();
	responsePayload = new DTO_Response();
	defaultMockBody = '{"success": true, "messageId": "msg-12345"}';
}
  • In unit tests, the framework automatically returns this JSON as the mock HTTP response (200 OK) when no higher-priority mock is registered.
  • Outside a unit test the canned answer never stands in: in production and in a sandbox the handler makes its real call, whether or not the caller named a credential.
  • To answer canned data outside tests on purpose, enable the MockAllAPIs feature flag, or tick Mocking Enabled (MockingEnabled__c) on the service's API Setting and turn on the MockSelectedAPIs feature flag for the users who should get mock answers (see Declarative Mock Mode).

API_MockFactory (Programmatic Mocking) ​

When a single canned response isn't enough (for example, different responses in different tests, or simulated errors), register a mock in code. API_MockFactory lets you set this up with short chained calls:

apex
// Register a custom mock response
API_MockFactory.forService(API_SendEmail.class.getName())
	.body('{"messageId":"msg-123"}')
	.statusCode(200)
	.register();

// Register a 500 error mock
API_MockFactory.registerErrorMock(API_SendEmail.class.getName());

// Register a parse-fail mock (200 OK with unparseable body)
API_MockFactory.registerParseFailMock(API_SendEmail.class.getName());

// Clear all registered mocks
API_MockFactory.clearMocks();

MockBuilder methods (all return MockBuilder for chaining):

MethodDescription
.body(String)Response body (supports &#123;&#123;request.field&#125;&#125; interpolation)
.statusCode(Integer)HTTP status code
.status(String)HTTP status text
.withHeader(String, String)Add a response header
.withHeaders(Map<String, String>)Add multiple response headers
.fromResponse(HttpResponse)Populate from an existing HttpResponse
.withFailureRate(Integer)Percentage of requests to fail randomly (0-100)
.withTransportFailure()The callout throws before any response exists, so the caller sees no status code at all
.register()Register the mock in the factory

.withTransportFailure() is the one that ignores the rest of the registration: a callout that never reached the other end has no body, status or headers to return. Use it to prove that your code treats a connection that failed outright differently from a request that came back with a bad status.

Call Verification ​

As well as returning a fake response, the factory records what your code actually sent, so a test can assert that a mock was called, or never called, and that the last request body held the right field:

apex
// Check if a service was called
Assert.isTrue(API_MockFactory.wasCalled(API_SendEmail.class.getName()), 'Service should be called');

// Verify the service was never called
Assert.isTrue(API_MockFactory.wasNeverCalled(API_SendEmail.class.getName()), 'Should not be called');

// Verify last request contained specific data
Assert.isTrue(
	API_MockFactory.lastRequestContains(API_SendEmail.class.getName(), '"recipient"'),
	'Request should contain recipient'
);

Response Interpolation ​

Sometimes a realistic mock needs to reflect the request back, for example echoing an id the caller sent. Drop &#123;&#123;request.field&#125;&#125; placeholders into the mock body and the framework fills them from the actual request:

apex
API_MockFactory.forService(API_EchoService.class.getName())
	.body('{"echoId":"{{request.id}}","echoName":"{{request.data.name}}"}')
	.statusCode(200)
	.register();

// When request contains {"id":"12345","data":{"name":"Acme"}}
// Response becomes: {"echoId":"12345","echoName":"Acme"}

Supported patterns:

  • &#123;&#123;request.fieldName&#125;&#125;: Top-level field
  • &#123;&#123;request.nested.field&#125;&#125;: Nested field access via dot notation

Fault Injection ​

Code that only ever sees success in tests can hide weak error handling. You can make a mock fail a chosen percentage of the time, so you can prove your retry and fallback paths actually work:

apex
// 50% of requests fail randomly with 500
API_MockFactory.forService(API_UnreliableService.class.getName())
	.body('{"success":true}')
	.statusCode(200)
	.withFailureRate(50)
	.register();

Declarative Mock Mode ​

You can also switch mocking on through configuration alone, with no Apex, which is handy for sandbox and demo orgs where you'd rather not deploy code. Three ways to do it:

Every service, through a feature flag: Enable the MockAllAPIs feature flag to mock every outgoing service, or the MockAllInboundAPIs feature flag to mock every incoming service.

One service at a time: Two settings work together, and the rule is the same for outgoing and incoming services.

  • Mocking Enabled (MockingEnabled__c) on the service's ApiSetting__mdt record picks the service.
  • The Mock Selected APIs feature flag (MockSelectedAPIs) decides which users get mock answers from those services: only the users the flag is on for.

A service answers mock data only when its active API Setting has the box ticked and the flag is on for the user the call runs as. The box alone, or the flag alone, mocks nothing. What mock data means depends on the direction:

  • Outgoing service: it answers a matching ApiMock__mdt record if you added one, otherwise the handler's canned body. A service with neither fails with a configuration error: "No mock response is set up for (the service class). Add an API Mock record for this service, or clear Mocking Enabled on its API Setting."
  • Incoming service: the request is answered from a matching ApiMock__mdt record instead of running the handler's own code, or with a default body when no record matches.

The box picks the service; ApiMock__mdt.MatchRequestBodyPattern__c picks the answer for each request.

Which user does the flag check? Each call checks the flag for the user it runs as:

  • a call from a page or a flow: the user who started it;
  • a scheduled flow or a retry: the user who runs it;
  • an incoming request: the user the caller signs in as.

So to mock an incoming service, turn the flag on for the user your caller signs in as (often an integration user).

The flag ships off. Ticking the box changes nothing until you turn the flag on.

  • The MockSelectedAPIs record arrives with the package active, with Is Enabled By Default unticked and no strategies.
  • An incoming service that had the box ticked before you upgraded runs its own code until you turn the flag on for the users who call it.
  • Health Check's Selected API Mocking row lists every active API Setting with the box ticked and says whether those services answer mock data for you. It also warns when Mock All APIs or Mock All Inbound APIs is on for you.

Turn the flag on. Pick the scope you need:

  • For the whole org: in Setup, open Custom Metadata Types > Feature Flag > Manage Feature Flags, edit Mock Selected APIs and tick Is Enabled By Default. This works only while the flag has no active strategy records.

  • For one user, or a small group:

    1. Create a permission set of your own (for example Mock_Selected_APIs_Users) and assign it to the users who should get mock answers.
    2. Add a FeatureFlagStrategy__mdt record (Custom Metadata Types > Feature Flag Strategy > Manage Feature Flag Strategies > New) with Feature Flag set to Mock Selected APIs, Type set to Permission Set Group, Target set to the permission set's API name, Is Active ticked and Order 1.

    Users without the permission set fall back to Result On No Match, which ships unticked, so for them the flag stays off.

  • Decided in your own code: point a strategy at a custom handler class (see Custom Strategy Handlers in the Feature Flags guide).

    • This handler turns the flag on only for users whose username ends with the text in the strategy's Target.
    • Sandbox usernames end with the sandbox name (for example .uat), so the flag stays off in production even if the same records are deployed there:
apex
/**
 * @description Turns a flag on only for users whose username ends with the text in the strategy's Target field.
 *
 * @author your.name@company.com
 *
 * @group Feature Flags
 *
 * @date October 2026
 */
global with sharing class FF_UsernameSuffixStrategy implements kern.UTIL_FeatureFlag.INT_FeatureFlagStrategy
{
	/**
	 * @description Checks whether the running user's username ends with the text in Target__c.
	 *
	 * @param flag The feature flag being evaluated.
	 * @param strategyToEvaluate The strategy record carrying the username ending in Target__c, for example .uat
	 *
	 * @return True when the running user's username ends with that text; false when it does not, or when Target__c is blank.
	 */
	public Boolean isEnabled(kern__FeatureFlag__mdt flag, kern__FeatureFlagStrategy__mdt strategyToEvaluate)
	{
		String usernameEnding = strategyToEvaluate.kern__Target__c;
		return String.isNotBlank(usernameEnding) && UserInfo.getUserName().endsWithIgnoreCase(usernameEnding);
	}
}

Wire it with a strategy record whose Feature Flag is Mock Selected APIs, Custom Handler Class is FF_UsernameSuffixStrategy, Target is your sandbox's ending (for example .uat), Is Active is ticked and Order is 1. Type can be any value: once Custom Handler Class is filled in, the framework ignores it.

Do not create a feature flag of your own named MockSelectedAPIs. The framework keeps one flag for each name, so a record of yours with that name would decide the flag in place of the packaged one. Add strategy records to the packaged flag instead.

Metadata Mocks (via ApiMock__mdt):

Configure mock responses in custom metadata for sandbox and demo environments without deploying code changes. ApiMock__mdt records support response bodies, status codes, headers, request matching patterns, delay simulation, and failure rates.


Disabling APIs ​

Switch APIs off through configuration, with no deployment: stop a problem call during an incident and turn it back on later the same way. You can disable everything or just one service:

ScopeHow
All APIs (hierarchy)ApiRuntimeSwitch__c.DisableAllApis__c = true (per user/profile/org)
All APIs (feature flag)Enable the DisableAllAPIs feature flag
Per-ServiceSet IsActive__c = false on the service's ApiSetting__mdt record
Per-Service (feature flag)Set BypassFeatureFlag__c on ApiSetting__mdt to a feature flag name; when enabled, the service is bypassed

Performance Monitoring ​

The framework times each stage of every call and records it, so you can spot which integrations are slow and why without adding any instrumentation of your own. The fields say where the time went: waiting on the other system, your own processing, or the database save.

FieldDescription
CalloutDurationMs__cTime spent in HTTP callout (milliseconds)
HandlerDurationMs__cTime spent in handler logic
CommitDurationMs__cDatabase commit time
TotalDurationMs__cTotal end-to-end time

Access in code: read the four fields from the call's ApiCall__c record through a selector of your own on that object. Write it once; the other reads of API Call records on this page use it too.

  • It extends kern.SEL_Base, and getFields() lists the fields those reads need.
  • It reads in user mode (while the UserModeQueries_Enabled flag is on, as it ships): the running user's object permissions, field permissions and record sharing all apply. A user without access to a field gets a QueryException. Do not override systemModeRequired() in it.
  • API Call records are private, so a user-mode read returns only the calls that sharing shows the reader. To read every call, the reader needs View All on API Call: the Kern Administrator and Kern API Issue Resolver permission sets both grant it.
  • getFields() leaves out the request and response bodies (Request__c and Response__c), so its other reads on this page need no access to them. Only findByIdWithBodies adds them, for one call at a time.
  • On a managed install the object and its fields carry kern__, as written here.
apex
/**
 * @description Reads the API call records the framework saves. Every read goes through a selector, so you keep a short
 * one of your own for API calls. It reads in user mode: the person running it needs read access to API calls.
 */
public with sharing class SEL_ApiCalls extends kern.SEL_Base
{
	/**
	 * @description Creates the selector for API call records.
	 */
	public SEL_ApiCalls()
	{
		super(kern__ApiCall__c.SObjectType);
	}

	/**
	 * @description Lists the fields every read returns. The request and response bodies are left out.
	 *
	 * @return The fields.
	 */
	public override List<SObjectField> getFields()
	{
		return new List<SObjectField>
		{
			kern__ApiCall__c.kern__ServiceName__c,
			kern__ApiCall__c.kern__Direction__c,
			kern__ApiCall__c.kern__IdempotencyKey__c,
			kern__ApiCall__c.kern__IdempotencyKeyBodyHash__c,
			kern__ApiCall__c.kern__CalloutDurationMs__c,
			kern__ApiCall__c.kern__HandlerDurationMs__c,
			kern__ApiCall__c.kern__CommitDurationMs__c,
			kern__ApiCall__c.kern__TotalDurationMs__c
		};
	}

	/**
	 * @description Reads one API call with its request and response bodies. The bodies are read only here, so the
	 * other reads need no access to them.
	 *
	 * @param apiCallId The Id of the API call to read.
	 *
	 * @return The API call, with its request and response bodies.
	 */
	public kern__ApiCall__c findByIdWithBodies(Id apiCallId)
	{
		return (kern__ApiCall__c)query
			.addFields(new List<SObjectField>{ kern__ApiCall__c.kern__Request__c, kern__ApiCall__c.kern__Response__c })
			.condition(kern__ApiCall__c.Id).equals(apiCallId)
			.getFirst();
	}
}

Then read the timing fields of one call through it (in this sample, apiCallId holds that record's Id). Its query starts a read with the selector's fields, which include the four timing fields.

apex
kern__ApiCall__c apiCall = (kern__ApiCall__c)new SEL_ApiCalls().query
	.condition(kern__ApiCall__c.Id).equals(apiCallId)
	.getFirst();

Decimal calloutTime = apiCall.kern__CalloutDurationMs__c;
Decimal handlerTime = apiCall.kern__HandlerDurationMs__c;
Decimal commitTime = apiCall.kern__CommitDurationMs__c;
Decimal totalTime = apiCall.kern__TotalDurationMs__c;

Batched Outbound Calls ​

You mark calls as queued, and a scheduled job works through them for you later, in the background. Use it when you don't want to make a callout right now, for example to spread load or to send calls on a schedule.

Scheduled Processing:

The framework includes SCHED_PerformBatchedCallouts to process the queued API calls. The sample below schedules it hourly, the fastest System.schedule allows; to run it more often, put it on the job runner instead:

apex
// Schedule batched callout processing.
System.schedule
(
	'Process Batched API Calls',
	'0 0 * * * ?',
	new SCHED_PerformBatchedCallouts()
);

You can also schedule it with no code: a ScheduledJob__c record whose class name is SCHED_PerformBatchedCallouts runs it on that record's schedule (see Async Processing - Guide).

How It Works:

  1. Create queue items with status 'Batched'
  2. Scheduled job changes status to 'Queued'
  3. Platform event or async processor picks up queued items
  4. Factory manager executes the calls

Safe Mode ​

Safe Mode runs an API handler as a dry run, then rolls back every database change at the end so nothing is left behind.

  • What it is for: seeing what a handler would do without changing any data in your org, for instance to replay a failed request or to try a new handler before it goes live.
  • Inside the framework: it is used internally for testing, debugging, and validating API behaviour without persisting changes.

Dry-run testing of your own APIs. To exercise an inbound API without persisting changes, write @IsTest methods with Test.startTest() / Test.stopTest() and let the test-mode rollback do the work. To exercise an outbound API without making a real callout, mock it via kern.API_MockFactory.forService(serviceName).body(json).register(). Both give you a clean dry run, and both run in your own namespace.

How you reach Safe Mode:

  • Without writing any Apex: through the API Test Harness screen described below, which runs in Safe Mode by default. Pick a service, run it, read the response, and nothing the handler wrote to the database is left behind.
  • Everywhere else: the framework turns Safe Mode on for itself whenever it needs a dry run, so you get the same rollback without setting anything up.

Behavior ​

AspectBehavior
DML OperationsExecuted then rolled back
TriggersFire normally
Validation RulesExecute and can block
Workflows/FlowsExecute but rolled back
HTTP CalloutsStill sent unless Mocking is on
EmailsNOT rolled back
Platform EventsRolled back (deferred publishing)
Governor LimitsConsumed as normal
ApiCall__c logsRolled back (not persisted)

Use Cases ​

  • Debugging failed APIs: replay a request with Safe Mode to inspect behaviour without leaving database changes behind (turn Mocking on as well if the callout itself must not reach the endpoint)
  • Validating new API handlers: test end-to-end flow before enabling in production
  • Demo environments: execute APIs without creating real records
  • Test Harness: the apiTestHarnessForm LWC uses Safe Mode by default

API Test Harness (LWC and Tab) ​

The API Test Harness is a point-and-click screen where you pick a service, fill in parameters, run it, and read the response, so you can exercise an inbound or outbound API by hand without writing Apex.

It's a Lightning Web Component, apiTestHarnessForm, presented as a full-page workspace. It ships with a dedicated ApiTestHarness FlexiPage + Custom Tab, so you reach it from the Kern Home page (or any nav menu) without any App Builder configuration.

Features ​

  • Two-column page layout: configuration on the left, response preview on the right
  • Service discovery: auto-populates available services from ApiSetting__mdt filtered by direction
  • Direction toggle: switch between inbound and outbound APIs, reloads the service list automatically
  • Key-value parameter grid: dynamic rows for outbound parameters (add/remove/replacement-row for optional rows), serialised to the Apex controller as a structured List<DTO_NameValue> inside a single JSON request payload (avoids the comma/equals footgun of delimited strings)
  • Shows what a service needs before you run it: pick an outbound service and the form reads the inputs it declares through getRequiredInputs(), along with whether it needs a triggering record (requiresTriggeringRecord).
    • Those parameters arrive as rows marked "Required" whose names are fixed, so you only fill in the values; one empty optional row follows them for anything else.
    • The Record ID field reads "Record ID (optional)" unless the service needs one.
    • Execute stays disabled, with a short line underneath naming what is still missing, until every required value is present and, when the service needs a record, the Record ID you type is 15 or 18 characters.
    • The same checks still run on the server, so a call built outside the harness is validated exactly as before.
  • Execution Settings safety bar: 4-state combined indicator for Safe Mode and Mocking:
    • Safe Mode · Real callouts (blue info): DML rolled back, but the callout still reaches the real endpoint unless you also turn Mocking on
    • Full Sandbox (green success): DML rolled back AND responses mocked
    • Live DML · Mocked callouts (amber warning): persistent DML but mocked external calls
    • LIVE (red error + SLDS alert-texture stripes): fully persistent, maximum risk
  • Destructive Execute variant: when Safe Mode is off, the Execute button turns red with a utility:warning icon and "Execute (Live)" label
  • Reset button: clears direction, service, parameters, toggles, and result in one click
  • Response preview: status badge (dynamically themed by isSuccess / isAborted / HTTP 4xx-5xx), metrics grid, Request/Response/Errors tabs with JSON viewers
  • API Call Id hyperlink: when Safe Mode was off on execution, the persisted ApiCall__c record Id renders as a clickable link that navigates to the record page; when Safe Mode was on (no persisted record), the Id is plain text
  • Sticky config column: on wide viewports, the left-side configuration panel stays pinned while the user scrolls the response preview, so Execute and Reset stay visible
  • Capped scroll regions: inner JSON viewers and header tables scroll internally rather than stretching the whole page, so very large responses stay manageable
  • Credential headers shown redacted: the Request Headers and Response Headers tables, and their copy actions, replace the value of Authorization, Proxy-Authorization, Cookie, Set-Cookie, X-Api-Key, Api-Key, X-Auth-Token and any header whose name contains secret, password, passwd, token or credential with [REDACTED], so a screenshot or a pasted header block never carries a session token or an API key

Deployment ​

Ships as part of Kern with three metadata artifacts, no App Builder wiring required:

  • ApiTestHarness.flexipage-meta.xml: the App Page that hosts the form
  • ApiTestHarness.tab-meta.xml: the Custom Tab referencing the FlexiPage
  • Administrator.permissionset-meta.xml: grants tab visibility via <tabSettings>

Users navigate to /lightning/n/ApiTestHarness or click the API Test Harness tool card on Kern Home to open it. The apiTestHarnessForm LWC is also exposed to lightning__AppPage and lightning__HomePage if you want to embed it elsewhere.


Idempotency (Inbound APIs) ​

Idempotency means a repeated request is recognised and not re-run: the caller can retry safely.

Here is the problem this solves. A caller sends you a request, the network drops before they get the answer, and they don't know whether you processed it, so they retry. Without protection, that retry runs a second time and you get a duplicate record.

There are two cases, and the framework treats them differently:

  • Same request sent twice (a genuine retry): the framework returns the answer it already produced the first time, with HTTP 200. It does not run the work again, so no duplicate.
  • Same key, but a different request body (usually a caller bug, where they reused the key but changed the payload): the framework refuses with HTTP 409 instead of silently masking the change, so the mismatch surfaces rather than hiding.

Turn it on per-service with kern__ApiSetting__mdt.IdempotencyEnabled__c = true. Once enabled:

  • callers send a unique Idempotency-Key HTTP header on each request (a tracking value the caller picks for that one request);
  • the framework matches it against kern__ApiCall__c.IdempotencyKey__c to spot a repeat;
  • the header name is matched without regard to case, so a caller that sends idempotency-key in lower case is recognised too.

A key belongs to the service and to the user who sent it. A repeat is a request with the same key, sent to the same service by the same user.

  • The same key sent to another service, or by another user, is a separate request: it is run, and it never gets another request's stored answer.
  • So ask each caller to send a fresh value, such as a UUID (a long random identifier), for every new request, and to reuse it only when sending that same request again from the same integration user.
  • The same key also ties a caller's retry to an earlier failure; see When a request fails.

What gets stored ​

When idempotency is enabled and a caller sends an Idempotency-Key header, the framework stores these fields on ApiCall__c after it has processed the first call:

  • IdempotencyKey__c: the raw header value, indexed as an external ID so a repeat can be looked up quickly
  • IdempotencyKeyBodyHash__c: a short fingerprint of the request body (a SHA-256 hex digest), used to tell whether a later request that reuses the same key actually carries the same body or a different one (see "Replay behaviour" below)
  • IsIdempotencyHit__c: true if the answer was returned from an earlier call's record without re-running the handler; false for first calls

Where the body fingerprint is kept:

  • Incoming calls: the body fingerprint is computed once per call, and it is stored on every incoming call, with or without a key. Running an issue's request again compares the stored body with it, to prove the body was not changed or cut.
  • Outbound calls leave IdempotencyKeyBodyHash__c blank. For an outbound call, the caller decides the key explicitly by stamping it via UTIL_HttpClient's withIdempotencyKey() (stored on IdempotencyKey__c), rather than the framework computing a fingerprint from the body.

Replay behaviour ​

The framework's replay decision is a three-way branch on the inbound request:

Replay scenarioStored hash on existing recordNew request body hashFramework response
Same key, same body (network retry, idempotent replay)matchesmatchesHTTP 200 + cached response from Response__c
Same key, different body (caller bug or stale-edit retry)populateddiffersHTTP 409 with JSON body referencing the original ApiCall.Id
Same key, legacy record (created before body-hash detection shipped)nullanyHTTP 200 + cached response (legacy passthrough, see "Backward compatibility")

These rows apply when an earlier call with the key completed. When no earlier call with the key completed (they failed or were refused), the request runs, and it is linked to the failure as When a request fails describes.

The HTTP 409 response body shape:

json
{
  "error": "Idempotency-Key reused with different request body",
  "originalApiCallId": "a01ABC0000xyz123"
}

Callers can parse originalApiCallId and read the original ApiCall__c record (through the SEL_ApiCalls selector above) to reconcile what their first request actually committed.

Handling 409 in callers ​

An HTTP 409 from an inbound endpoint means the same Idempotency-Key was previously used to commit a different request body. Three reasonable client-side responses:

  1. Investigate the divergence: read the original call through the SEL_ApiCalls selector above (new SEL_ApiCalls().findByIdWithBodies(originalApiCallId), which adds Request__c) and compare the stored Request__c against the new payload. Most often the caller has buggy retry logic that mutates the request body before retrying.
  2. Use a new key for the new payload: if the caller legitimately wants to send a different request, generate a fresh Idempotency-Key. Reusing the same key with a different body is a contract violation per the IETF idempotency-key draft.
  3. Surface the conflict to the caller's user: for human-driven workflows (e.g. a form submission), present the original response so the user knows their first attempt succeeded and the second was a duplicate.

HTTP 409 is only returned when both bodies hash differently (see Replay behaviour). Same-body replays continue to return HTTP 200 with the cached response, the standard idempotent-replay path.

Backward compatibility ​

ApiCall__c records created before the body-hash field shipped have IdempotencyKeyBodyHash__c = null.

  • Legacy records: the framework cannot detect divergence on these records, so it falls through to the cached-response path (HTTP 200) regardless of whether the new request body matches the original. This preserves pre-existing behaviour for legacy data.
  • Forward-going records (created after the body-hash check shipped) get the full 409 detection.
  • No backfill: there is no migration to backfill the hash on legacy records; the field stays null and those records are treated as legacy passthroughs forever.

To audit which records have the hash populated, read them through the SEL_ApiCalls selector above. Its query returns the selector's fields, which include kern__ServiceName__c, kern__IdempotencyKey__c and kern__IdempotencyKeyBodyHash__c. On a managed install the object and fields carry kern__, as the sample writes them.

apex
// Records with body-hash detection enabled
List<kern__ApiCall__c> withHash = new SEL_ApiCalls().query
	.condition(kern__ApiCall__c.kern__IdempotencyKey__c).isNotNull()
	.condition(kern__ApiCall__c.kern__IdempotencyKeyBodyHash__c).isNotNull()
	.condition(kern__ApiCall__c.kern__Direction__c).equals('Inbound')
	.toList();

// Legacy records (no body hash) — replay behaviour falls through to cached response
List<kern__ApiCall__c> legacyRecords = new SEL_ApiCalls().query
	.condition(kern__ApiCall__c.kern__IdempotencyKey__c).isNotNull()
	.condition(kern__ApiCall__c.kern__IdempotencyKeyBodyHash__c).isNull()
	.condition(kern__ApiCall__c.kern__Direction__c).equals('Inbound')
	.toList();

Logging and Monitoring ​

The framework records every call, every error, and every payload automatically. When an integration misbehaves in production, the answer to "what actually happened?" is already waiting instead of being lost.

Where Things Are Logged ​

ComponentLocationDetails
All API CallsApiCall__cRequest, response, status, timing
Large PayloadsContentVersionFiles linked to queue item
ErrorsApiCall__c.ErrorMessages__cError messages and stack traces
FailuresApiIssue__cPersistent failure records (if enabled)
Application LogsLogEntryEvent__e Platform EventVia LOG_Builder: configure the log with short chained calls, then one call writes it

Automatic Web Service Context ​

Every log you write during a call is automatically stamped with details about that call (which service, which endpoint, which HTTP method), so a log line never leaves you guessing which integration produced it.

The framework adds this context to all LOG_Builder calls during API execution, and it shows up in the ContextData__c field of LogEntry__c records.

Automatic Context Fields:

FieldWhen SetDescription
serviceNameconfigure()The API handler class name
endpointconfigure()The endpoint URL being called
httpMethodconfigure()The HTTP method (GET, POST, etc.)
statusCodeAfter calloutHTTP response status code (outbound only)
calloutDurationMsAfter calloutCallout duration in milliseconds (outbound only)

How It Works:

You log normally. Any LOG_Builder call made during API processing picks up the web service context for you, so you do not have to pass those fields in by hand:

apex
public inherited sharing class API_CustomerSync extends API_Outbound
{
	public override void onSuccess()
	{
		super.onSuccess();

		// This log entry automatically includes web service context
		LOG_Builder.build().info('Processing customer sync').emitAt('API_CustomerSync.onSuccess');
		// ContextData__c includes: serviceName, endpoint, httpMethod, statusCode, calloutDurationMs
	}
}

Correlation with Other Logs:

Correlation gives all the logs of one user action one shared correlation ID, so you can pull up the whole story of one request instead of hunting through unrelated log lines. A single user action often spans several steps: your own code, the API call, and whatever runs afterwards.

apex
// Before calling the API
LOG_Builder.startCorrelation();
LOG_Builder.build().info('Initiating customer sync').emitAt('MyService.syncCustomer');

// Execute API - context is automatically maintained
API_Dispatcher.execute(queueItems);

// All logs share the same correlationId for easy debugging

Context Cleanup:

Once a call finishes, the framework clears the web service context for you. That way later logs in the same transaction don't accidentally pick up the previous call's details and point you at the wrong integration.

Monitoring API Health ​

Watch the health of your integrations with ordinary Salesforce reports and list views, no extra tooling required: every call is recorded as an ApiCall__c record.

List View: Recent API Calls (the filter a list view or report uses, written as a query; not code for a class)

soql
SELECT Name, ServiceName__c, Status__c, StatusCode__c, CreatedDate, ErrorMessages__c
FROM ApiCall__c
WHERE CreatedDate = LAST_N_DAYS:7
ORDER BY CreatedDate DESC

Dashboard Metrics:

  • Success rate by service
  • Average response time
  • Failed calls requiring retry
  • Most common error messages

Accessing Large Payloads ​

  • A body that fits its field: read it with findByIdWithBodies on your own SEL_ApiCalls selector (Performance Monitoring).
  • A body that did not fit: read the file, as below.

A request or response body can be too big to fit in a text field. When that happens the framework stores the full body as a file (a ContentVersion) linked to the queue item, so nothing is truncated or lost. The file is first published on the call record, and the title of the request body's file starts with RequestBody.

Fetch that full body back through the framework's kern.SEL_ContentVersion selector:

  • findByFirstPublishLocationId returns the latest version of each file first published on the call, with its Title and VersionData. It finds a file only while the file has one version, which is how the framework writes them. If someone adds a second version, the new version has no first-published location and the old one is no longer the latest, so neither is returned.
  • SEL_ContentVersion reads in system mode: it skips the running user's object and field permission checks, and record sharing follows your class. So only show the body to a user who may read the call's Request__c and Response__c.
apex
// Get the files first published on the call record
List<ContentVersion> versions = new kern.SEL_ContentVersion().findByFirstPublishLocationId(queueItem.Id);

for(ContentVersion version : versions)
{
	if(version.Title.contains('RequestBody'))
	{
		String fullRequest = version.VersionData.toString();
	}
}

Testing ​

To stand in a fake response instead of calling the real system, see Mock Mode and API_MockFactory.

Overview of Test Helper Classes ​

The framework gives you a set of test helper classes that take the boilerplate out of web-service tests, so each test says what it verifies instead of how to wire it up. Without them, a test needs a lot of setup: building the request, creating the queue record, running the call, then checking the status and the logged result.

Helper ClassPurposeUsed For
API_OutboundTestHelperTest outbound REST APIsSuccessful calls, failed calls, aborted calls, parse failures
API_InboundTestHelperTest inbound REST APIsSetting up REST context, validating aborted calls
SEL_ApiCallAssert queue item statusVerifying service completion, abortion, or failure
TST_FactoryCreate test dataGenerating ApiCall__c records for testing
TST_BuilderBuild test recordsCreating test data with proper relationships

Key Benefits:

  • ✅ Cuts most of the set-up code from each test
  • ✅ Consistent testing patterns across all APIs
  • ✅ Automatic queue item creation and assertion
  • ✅ Built-in validation of framework behaviour
  • ✅ Cleaner, more maintainable tests

Testing Outbound APIs ​

Using API_OutboundTestHelper ​

The API_OutboundTestHelper class lets you verify that an outbound call succeeded, failed, or was aborted, without writing the setup-and-assert plumbing yourself.

Key Methods:

MethodPurposeReturns
assertCallSuccessful(serviceName, recordId)Test successful API executionAPI handler instance
assertCallSuccessful(serviceName, recordId, parameters)Test with custom parametersAPI handler instance
assertCallFailed(queueItems)Test failed API callsList of API handlers
assertCallAborted(serviceName, recordId)Test aborted callsAPI handler instance

What These Methods Do Automatically:

  1. Create ApiCall__c queue item using TST_Factory
  2. Execute the API via API_Dispatcher
  3. Assert the expected status (completed, failed, aborted)
  4. Return the handler for additional assertions

Complete Outbound Test Example ​

apex
/**
 * @description Unit tests for API_PostExample outbound API.
 *
 * @see API_PostExample
 */
@IsTest(seeAllData=false isParallel=true)
private class API_PostExample_TEST
{
	/**
	 * @description Validates successful API call with parameters
	 */
	@IsTest
	private static void successfulCallReturnsResponse()
	{
		API_Base handler = API_OutboundTestHelper.assertCallSuccessful(API_PostExample.class.getName(), UserInfo.getUserId());

		Assert.isNotNull(handler, 'Handler should not be null');

		// Verify queue item was created and marked as completed
		List<ApiCall__c> queueItems = SEL_ApiCall.assertServiceCompleted(API_PostExample.class.getName());
		Assert.areEqual(1, queueItems.size(), 'Should have one queue item');
		Assert.isNotNull(queueItems[0].Response__c, 'Response should be logged');
	}

	/**
	 * @description Validates API call with triggering Account record
	 */
	@IsTest
	private static void apiCallWithTriggeringObjectReferencesRecord()
	{
		Account testAccount = (Account)TST_Builder.of(Account.SObjectType)
			.withOverride(Account.Name, 'Test Company')
			.build();

		API_Base handler = API_OutboundTestHelper.assertCallSuccessful
		(
			API_PostExample.class.getName(),
			testAccount.Id
		);

		List<ApiCall__c> queueItems = new SEL_ApiCall().findByServiceName
		(
			API_PostExample.class.getName()
		);
		Assert.areEqual(testAccount.Id, queueItems[0].TriggeringRecordId__c, 'Should reference account');
	}

	/**
	 * @description Validates API abortion when all outbound calls are disabled
	 */
	@IsTest
	private static void disabledApiAbortsWithError()
	{
		TST_Factory.newFeatureFlag('DisableAllAPIs');

		API_Base handler = API_OutboundTestHelper.assertCallAborted
		(
			API_PostExample.class.getName(),
			null
		);

		Assert.isTrue(handler.result.isAborted, 'Call should be aborted');
		Assert.isFalse(handler.result.errors.isEmpty(), 'Should have error messages');

		// Verify queue item shows aborted status
		List<ApiCall__c> queueItems = SEL_ApiCall.assertServiceAborted
		(
			API_PostExample.class.getName(),
			'API has been disabled'
		);
		Assert.areEqual(1, queueItems.size());
	}

	/**
	 * @description Validates bulk processing of multiple API calls
	 */
	@IsTest
	private static void bulkApiCallsProcessAllRecords()
	{
		List<ApiCall__c> queueItems = new List<ApiCall__c>();
		for(Integer i = 0; i < 5; i++)
		{
			queueItems.add
			(
				TST_Factory.newOutboundApiCall
				(
					API_PostExample.class.getName(),
					UserInfo.getUserId()
				)
			);
		}

		Test.startTest();
		List<API_Base> handlers = API_Dispatcher.execute(queueItems);
		Test.stopTest();

		Assert.areEqual(5, handlers.size(), 'Should process all 5 API calls');

		List<ApiCall__c> completedItems = SEL_ApiCall.assertServiceCompleted
		(
			API_PostExample.class.getName()
		);
		Assert.areEqual(5, completedItems.size(), 'All calls should complete successfully');
	}
}

Using TST_Factory for Queue Items ​

Use the factory when you need to build the queue item yourself rather than let a helper do it. It lets you set exactly the service name, triggering record, and parameters your test needs:

apex
/**
 * @description Creates outbound queue item with basic service name
 */
ApiCall__c queueItem1 = TST_Factory.newOutboundApiCall(
	'API_PostExample'
);

/**
 * @description Creates queue item with triggering object
 */
ApiCall__c queueItem2 = TST_Factory.newOutboundApiCall(
	'API_PostExample',
	accountId
);

/**
 * @description Creates queue item with parameters map
 */
ApiCall__c queueItem3 = TST_Factory.newOutboundApiCall(
	'API_PostExample',
	accountId,
	new Map<String, String>{ 'foo' => 'Test Title' }
);

/**
 * @description Creates queue item with single parameter
 */
ApiCall__c queueItem4 = TST_Factory.newOutboundApiCall(
	'API_PostExample',
	accountId,
	'foo',
	'Test Title'
);

Testing Inbound APIs ​

Using API_InboundTestHelper ​

The API_InboundTestHelper class pretends a real HTTP request arrived, in one call, so your test can get straight to verifying the response. An inbound test needs a request and response object in place before your endpoint runs, and setting that up by hand is fiddly.

Key Methods:

MethodPurpose
setupRestContext()Initializes RestContext.request and RestContext.response with default values
setupRestContext(DTO_Base dtoRequest)Sets up context and populates request body with serialized DTO
assertCallAborted(serviceName)Executes API and asserts it was aborted
assertCallAborted(serviceName, exceptionMessage)Asserts abortion with specific error message
assertCallAborted(serviceName, dtoRequest, exceptionMessage)Full setup with DTO and error validation

What setupRestContext() Does:

  1. Creates new RestRequest and RestResponse objects
  2. Sets Content-Type header to application/json
  3. Sets HTTP method to POST
  4. Sets default request URI to https://example.com/test
  5. Assigns to RestContext.request and RestContext.response

Complete Inbound Test Example ​

This test covers the illustrative API_PersonRetrieve and API_PersonUpdate handlers written earlier in this guide. Those classes and the CMN_ExternalReference__c field are not in the package; use your own.

apex
/**
 * @description Unit tests for API_PersonRetrieve inbound API.
 *
 * @see API_PersonRetrieve
 * @see REST_Person
 */
@IsTest(seeAllData=false isParallel=true)
private class API_PersonRetrieve_TEST
{
	/**
	 * @description Creates test Contact record for use in tests
	 */
	@TestSetup
	private static void setupTestData()
	{
		TST_Builder.of(Contact.SObjectType).withOverrides(new Map<SObjectField, Object>
		{
			Contact.LastName => 'Test Person',
			Contact.FirstName => 'John',
			Contact.Email => 'john.test@example.com',
			Contact.MobilePhone => '555-0100',
			Contact.CMN_ExternalReference__c => 'test-guid-12345'
		}).build();
	}

	/**
	 * @description Validates successful person retrieval with valid identity ID
	 */
	@IsTest
	private static void successfulRetrievalReturnsPersonData()
	{
		Contact testContact = (Contact)QRY_Builder.selectFrom(Contact.SObjectType)
			.addFields(new List<SObjectField>{Contact.Id, Contact.CMN_ExternalReference__c})
			.withLimit(1)
			.getFirst();

		API_InboundTestHelper.setupRestContext();
		RestContext.request.requestURI = RestContext.request.requestURI + '/' + testContact.CMN_ExternalReference__c;

		Test.startTest();
		System.runAs(TST_Factory.newUser('Standard User'))
		{
			REST_Person.getPerson();
		}
		Test.stopTest();
		String responseBody = RestContext.response.responseBody.toString();
		Map<String, Object> responseMap = (Map<String, Object>)JSON.deserializeUntyped(responseBody);

		Assert.areEqual('Test Person', responseMap.get('lastName'), 'Should return lastName');
		Assert.areEqual('John', responseMap.get('firstName'), 'Should return firstName');
		Assert.areEqual('john.test@example.com', responseMap.get('email'), 'Should return email');
		Assert.areEqual(200, RestContext.response.statusCode, 'Should return 200 OK');

		// Verify queue item was logged with completed status
		SEL_ApiCall.assertServiceCompleted(API_PersonRetrieve.class.getName());
	}

	/**
	 * @description Validates error handling when person is not found
	 */
	@IsTest
	private static void personNotFoundReturnsErrorResponse()
	{
		API_InboundTestHelper.setupRestContext();
		RestContext.request.requestURI = RestContext.request.requestURI + '/invalid-guid-99999';

		Test.startTest();
		System.runAs(TST_Factory.newUser('Standard User'))
		{
			REST_Person.getPerson();
		}
		Test.stopTest();

		Assert.areEqual(400, RestContext.response.statusCode, 'Should return 400 Bad Request');
		String responseBody = RestContext.response.responseBody.toString();
		Assert.isTrue(responseBody.contains('No person found'), 'Should contain error message');

		// Verify queue item was logged with aborted status
		SEL_ApiCall.assertServiceAborted(API_PersonRetrieve.class.getName(), 'No person found');
	}

	/**
	 * @description Validates missing identity ID returns validation error
	 */
	@IsTest
	private static void missingIdentityIdReturnsValidationError()
	{
		API_InboundTestHelper.setupRestContext();

		Test.startTest();
		REST_Person.getPerson();
		Test.stopTest();

		SEL_ApiCall.assertServiceAborted(API_PersonRetrieve.class.getName(), 'Identity Id not provided');
	}

	/**
	 * @description Validates update person with DTO modifies contact record
	 */
	@IsTest
	private static void updatePersonWithDtoModifiesContactRecord()
	{
		Contact testContact = (Contact)QRY_Builder.selectFrom(Contact.SObjectType)
			.addFields(new List<SObjectField>{Contact.Id, Contact.CMN_ExternalReference__c})
			.withLimit(1)
			.getFirst();

		API_PersonUpdate.DTO_Request updateRequest = new API_PersonUpdate.DTO_Request();
		updateRequest.identityId = testContact.CMN_ExternalReference__c;
		updateRequest.firstName = 'Jane';
		updateRequest.lastName = 'Updated';
		updateRequest.email = 'jane.updated@example.com';

		API_InboundTestHelper.setupRestContext(updateRequest);

		Test.startTest();
		REST_Person.editPerson();
		Test.stopTest();

		Contact updatedContact = (Contact)QRY_Builder.selectFrom(Contact.SObjectType)
			.addFields(new List<SObjectField>{Contact.Id, Contact.FirstName, Contact.LastName, Contact.Email})
			.condition(Contact.Id).equals(testContact.Id)
			.getFirst();
		Assert.areEqual('Jane', updatedContact.FirstName, 'FirstName should be updated');
		Assert.areEqual('Updated', updatedContact.LastName, 'LastName should be updated');
		Assert.areEqual('jane.updated@example.com', updatedContact.Email, 'Email should be updated');

		// Verify queue item shows successful completion
		SEL_ApiCall.assertServiceCompleted(API_PersonUpdate.class.getName());
	}

	/**
	 * @description Validates assertCallAborted helper detects missing required fields
	 */
	@IsTest
	private static void assertCallAbortedHelperDetectsMissingFields()
	{
		API_PersonUpdate.DTO_Request invalidRequest = new API_PersonUpdate.DTO_Request();

		Test.startTest();
		API_Base handler = API_InboundTestHelper.assertCallAborted(API_PersonUpdate.class.getName(), invalidRequest, 'Identity Id not provided');
		Test.stopTest();

		Assert.isTrue(handler.result.isAborted, 'Should be aborted');
		Assert.isTrue(handler.result.errors.contains('Identity Id not provided'), 'Should have validation error');
	}
}

Using SEL_ApiCall for Assertions ​

The SEL_ApiCall class gives you assertion methods to check API execution status, so a single line confirms the call completed, was aborted, or failed, and that the framework logged it.

Key Assertion Methods:

apex
/**
 * @description Asserts API completed successfully
 */
List<ApiCall__c> completedItems = SEL_ApiCall.assertServiceCompleted(
	'API_PersonRetrieve'
);

/**
 * @description Asserts API was aborted
 */
List<ApiCall__c> abortedItems = SEL_ApiCall.assertServiceAborted(
	'API_PersonRetrieve'
);

/**
 * @description Asserts API was aborted with specific error message
 */
List<ApiCall__c> abortedItems = SEL_ApiCall.assertServiceAborted(
	'API_PersonRetrieve',
	'No person found'
);

/**
 * @description Asserts API failed
 */
List<ApiCall__c> failedItems = SEL_ApiCall.assertServiceFailed(
	'API_PersonRetrieve'
);

/**
 * @description Asserts API failed with specific error phrase
 */
List<ApiCall__c> failedItems = SEL_ApiCall.assertServiceFailed(
	'API_PersonRetrieve',
	'Timeout'
);

What These Methods Do:

  1. Query ApiCall__c for the specified service name
  2. Assert that at least one queue item exists
  3. Assert that all queue items have the expected status
  4. Optionally assert error message contains the specified phrase
  5. Return the queue items for additional assertions

Query Methods:

apex
/**
 * @description Retrieves all queue items for a service
 */
List<ApiCall__c> items = new SEL_ApiCall().findByServiceName(
	'API_PersonRetrieve'
);

Batched outbound calls are picked up for you by the scheduled job described under Batched Outbound Calls, so there is nothing you need to query by hand to make them run.


Testing Best Practices ​

  1. Always use test helper classes - API_OutboundTestHelper and API_InboundTestHelper eliminate boilerplate
  2. Use TST_Builder for test data - Cleaner than manual record creation
  3. Test bulk scenarios - Create and process multiple queue items
  4. Use assertion methods - assertServiceCompleted(), assertServiceAborted(), assertServiceFailed()
  5. Verify queue items - Always check that ApiCall__c records were created correctly
  6. Test error scenarios - Missing parameters, invalid data, disabled APIs
  7. Use @TestSetup - Create common test data once for multiple test methods
  8. Test with different users - Use System.runAs() to test with API users
  9. Enable logging when needed - Set LOG_Builder.ignoreTestMode = true for log testing
  10. Test mock responses - Verify that mock classes return expected data

Common Test Patterns ​

Pattern 1: Simple Successful Outbound Call

apex
@IsTest
private static void successfulOutboundCallCompletesWithResponse()
{
	Test.startTest();
	API_Base handler = API_OutboundTestHelper.assertCallSuccessful(API_MyService.class.getName(), recordId);
	Test.stopTest();

	// Additional assertions on handler.result or handler.responsePayload
}

Pattern 2: Outbound Call with Parameters

apex
@IsTest
private static void outboundCallWithParametersExecutesCorrectly()
{
	Map<String, String> params = new Map<String, String>{ 'key' => 'value' };

	Test.startTest();
	API_Base handler = API_OutboundTestHelper.assertCallSuccessful(API_MyService.class.getName(), null, params);
	Test.stopTest();
}

Pattern 3: Inbound Call Setup

apex
@IsTest
private static void inboundCallProcessesRequestSuccessfully()
{
	API_InboundTestHelper.setupRestContext();
	RestContext.request.requestURI = RestContext.request.requestURI + '/someId';

	Test.startTest();
	REST_MyAPI.httpMethodName();
	Test.stopTest();

	SEL_ApiCall.assertServiceCompleted(API_MyImplementation.class.getName());
}

Pattern 4: Inbound Call with DTO

apex
@IsTest
private static void inboundCallWithDtoProcessesRequest()
{
	API_MyService.DTO_Request request = new API_MyService.DTO_Request();
	request.fieldName = 'value';

	API_InboundTestHelper.setupRestContext(request);

	Test.startTest();
	REST_MyAPI.httpMethodName();
	Test.stopTest();

	SEL_ApiCall.assertServiceCompleted(API_MyService.class.getName());
}

Pattern 5: Testing Abortion

apex
@IsTest
private static void abortedCallLogsErrorMessage()
{
	Test.startTest();
	API_Base handler = API_OutboundTestHelper.assertCallAborted(API_MyService.class.getName(), null);
	Test.stopTest();

	SEL_ApiCall.assertServiceAborted(API_MyService.class.getName(), 'Expected error message');
}

Virtual Methods Reference ​

Each step the base classes leave open for the parts unique to your integration is a method you can override:

  • what it is for, and what it does if you leave it alone;
  • when you would want to change it, with a worked example.

Common Base Methods (API_Base) ​

These methods are available in both inbound and outbound APIs.


getValidationErrors() ​

Purpose: Checks the request before any work starts and stops it cleanly if something is wrong, so a bad request fails fast with a clear message instead of part-way through.

Signature: global protected virtual List<String> getValidationErrors()

Default Behavior: Returns an empty list (no validation errors). Framework-level checks (disabled APIs, feature flags, runtime switches) are handled internally by performValidation(), so you do not need to call super.

When to Override:

  • Validating required parameters
  • Checking user permissions
  • Validating request payload structure
  • Querying and validating related data

Return Value: List of error message strings. An empty list means validation passed; non-empty aborts the request.

Example:

apex
/**
 * @description Validates required parameters before proceeding with API call.
 *
 * @return List of validation error messages, empty if validation passed
 */
public override List<String> getValidationErrors()
{
	List<String> errors = new List<String>();

	String userId = inputs.get('userId');
	if(String.isBlank(userId))
	{
		errors.add('userId parameter is required');
	}

	return errors;
}

getBody() ​

Purpose: Builds the body that gets sent in the HTTP request. Override it when the framework's default formatting does not match what the other system expects.

Signature: global protected virtual String getBody()

Default Behavior: Serializes requestPayload to JSON or XML.

When to Override:

  • Custom body formatting (multi-part form data, binary content)
  • Non-standard serialization
  • Custom XML structure

Return Value: String containing the request body

Note: Rarely needs to be overridden.


onSuccess() ​

Purpose: This is where you say what records should change once the callout has come back successfully, for example creating an Account from the response. You register the changes here and the framework saves them for you, after the callout, so you never trip the "callout with uncommitted work pending" error.

Signature: global protected virtual void onSuccess()

Default Behavior: No operations registered (empty method).

When to Override:

  • Creating records from API responses
  • Updating records based on API results
  • Logging activity (Tasks, Events, etc.)
  • Managing relationships

Important: Never run a plain DML statement (insert/update/delete) directly, because that would save outside the framework's ordering and could break the callout-before-save rule.

  • API_Base extends DML_Transaction, so the database methods (doInsert(), doUpdate(), doDelete(), doUpsert()) are already available to you.
  • Call them inside onSuccess() to register the records you want changed: the framework saves them as one batch after all callouts finish.

Saves here do not check the user's permissions. This applies to inbound and outbound services alike.

  • The framework saves the records you register in onSuccess() in system mode (SYSTEM_MODE), so it does not check the running user's object and field permissions.
  • It does this on purpose: the same save writes the framework's own record of the call, and that record must be kept even when the user has no access to it.
  • If a record must be saved with the running user's permissions, do not register it here. Save it with DML_Builder.newTransaction().withUserMode() in its own transaction instead.

Example:

apex
/**
 * @description Creates Account and updates Contact based on API response.
 */
public override void onSuccess()
{
	super.onSuccess();

	DTO_Response response = (DTO_Response)responsePayload;

	// Create Account from API response
	Account newAccount = new Account
	(
		Name = response.companyName,
		Industry = response.industry,
		ExternalId__c = response.externalId
	);
	doInsert(newAccount);

	// Update existing Contact
	Contact existingContact = queryContact();
	existingContact.Email = response.email;
	doUpdate(existingContact);
}

Outbound-Specific Methods (API_Outbound) ​

These methods are only available in outbound APIs.


getAuthorisationToken() ​

Purpose: Supplies the authorization value the call needs to prove who it is. Override it when a stored Named Credential is not enough and you have to build the token yourself.

Signature: global protected virtual String getAuthorisationToken()

Default Behavior: Returns empty string (authentication handled by Named Credential).

When to Override:

  • Custom authentication (OAuth, API keys, session-based)
  • Dynamic token management
  • Custom auth schemes

Return Value: Authorization header value (e.g., Bearer {token})

Example:

apex
/**
 * @description Provides OAuth token for API authentication.
 *
 * @return Bearer token for authorization
 */
public override String getAuthorisationToken()
{
	// Custom OAuth token logic
	return 'Bearer ' + getOAuthToken();
}

getHttpMethod() ​

Purpose: Sets which HTTP verb the call uses. The framework assumes POST, so override this when your endpoint expects a different verb.

Signature: global protected override virtual HttpMethod getHttpMethod()

Default Behavior: Returns HttpMethod.POST.

When to Override: When using GET, PUT, PATCH, or DELETE methods.

Return Value: HttpMethod enum value (HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH, HttpMethod.DELETE)

Example:

apex
/**
 * @description Specifies GET method for this API.
 *
 * @return GET HTTP method
 */
public override HttpMethod getHttpMethod()
{
	return HttpMethod.GET;
}

getQueryParameters() ​

Purpose: Adds the ?key=value parameters that get tacked onto the end of the URL, for cases where the other system reads options from the query string.

Signature: global protected virtual String getQueryParameters()

Default Behavior: Returns empty string.

When to Override: When adding URL query parameters.

Return Value: Query string (without leading ?)

Example:

apex
/**
 * @description Builds query parameters for the API call.
 *
 * @return Query string with format and version
 */
public override String getQueryParameters()
{
	List<String> params = new List<String>();
	params.add('format=json');
	params.add('version=2');
	return String.join(params, '&');
}

getRequiredInputs() ​

Purpose: Lists the parameters the call cannot run without, so the framework rejects an incomplete request up front rather than failing later with a confusing error. Declaring them here is also what the API Test Harness reads to seed its form: it fills in those parameter names for you and locks them, leaving you just the values to type.

Signature: global protected virtual Set<String> getRequiredInputs()

Default Behavior: Returns empty set.

When to Override: When your API requires specific parameters.

Return Value: Set of required parameter names

Example:

apex
/**
 * @description Defines required parameters for validation.
 *
 * @return Set of required parameter names
 */
public override Set<String> getRequiredInputs()
{
	Set<String> required = super.getRequiredInputs();
	required.add('userId');
	required.add('accountId');
	return required;
}

getResponseBody() ​

Purpose: Pulls out the part of the HTTP response you actually want to read. Override it when the useful data is buried inside a wrapper or arrives encoded.

Signature: global protected virtual String getResponseBody()

Default Behavior: Returns response.getBody().

When to Override:

  • Unwrapping nested response structure
  • Decoding encoded content

Return Value: Response body string


getResponseReplacementTokens() ​

Purpose: Rewrites awkward bits of the response JSON before Apex tries to read it, so keys that Apex cannot handle (reserved words, hyphens) become valid field names and the response parses cleanly.

Signature: global protected virtual void getResponseReplacementTokens(List<String> searchTokens, List<String> replaceTokens)

Default Behavior: No replacements.

When to Override: When response contains:

  • Reserved Apex keywords (class, type)
  • Hyphens in JSON keys (user-id → userId)
  • Special characters incompatible with Apex

Parameters:

  • searchTokens - List to populate with strings to find
  • replaceTokens - List to populate with replacement strings

Example:

apex
/**
 * @description Replaces reserved keywords and hyphens in response JSON.
 *
 * @param searchTokens List to populate with tokens to find
 * @param replaceTokens List to populate with replacement tokens
 */
public override void getResponseReplacementTokens(List<String> searchTokens, List<String> replaceTokens)
{
	super.getResponseReplacementTokens(searchTokens, replaceTokens);
	searchTokens.add('"user-id"');
	replaceTokens.add('"userId"');
	searchTokens.add('"class"');
	replaceTokens.add('"className"');
}

getTimeout() ​

Purpose: Sets how long the call waits for a reply before giving up. Lower it when a slow endpoint should fail quickly rather than tie up the transaction.

Signature: global protected virtual Integer getTimeout()

Default Behavior: Returns 120000 milliseconds (2 minutes).

When to Override: When a different timeout is needed.

Return Value: Timeout in milliseconds (max 120000)

Example:

apex
/**
 * @description Sets timeout to 1 minute.
 *
 * @return Timeout in milliseconds
 */
public override Integer getTimeout()
{
	return 60000; // 1 minute
}

getWebServiceEndPoint() ​

Purpose: Decides the exact URL the call goes to. Override it when the address changes per request, for example when a record ID has to be slotted into the path.

Signature: global protected virtual String getWebServiceEndPoint()

Default Behavior: Combines Named Credential URL with path from ApiSetting__mdt.EndpointPath__c.

When to Override:

  • Dynamic URL construction
  • URL parameter substitution
  • Path variables
  • Custom routing logic

Return Value: Complete endpoint URL

Example:

apex
/**
 * @description Builds endpoint URL with userId path parameter.
 *
 * @return Complete endpoint URL
 */
public override String getWebServiceEndPoint()
{
	String userId = inputs.get('userId');
	String basePath = super.getWebServiceEndPoint();
	return String.format(basePath, new List<String>{ userId });
}

prepareRequest() ​

Purpose: Fills in the data you want to send before the call goes out. Override it when the request needs more than the default fields, such as data from a related query or a computed value.

Signature: global protected virtual void prepareRequest()

Default Behavior: Calls requestPayload.populate(recordId, inputs).

When to Override:

  • Complex data transformations
  • Querying related data
  • Combining multiple data sources
  • Parameter processing

Example:

apex
/**
 * @description Populates request with timestamp and user info.
 */
public override void prepareRequest()
{
	super.prepareRequest();

	DTO_Request request = (DTO_Request)requestPayload;
	request.timestamp = Datetime.now();
	request.username = UserInfo.getUserName();
}

setHeaders() ​

Purpose: Adds the HTTP headers the request carries. Override it to send extra headers the other system expects, such as an API key or a tracking ID.

Signature: global protected virtual void setHeaders()

Default Behavior: Sets Content-Type and Accept headers to JSON.

When to Override:

  • Custom headers (API keys, tokens, correlation IDs)
  • Different content types
  • Additional authentication headers

Example:

apex
/**
 * @description Adds custom headers for API call.
 */
public override void setHeaders()
{
	super.setHeaders();
	request.setHeader('X-API-Key', getClientId());
	request.setHeader('X-Correlation-ID', UTIL_Random.randomUUID());
	request.setHeader('X-Client-Version', '2.0');
}

requiresTriggeringRecord ​

Purpose: Says whether the call must be tied to a specific Salesforce record. Leave it on for record-driven integrations; turn it off when the call stands on its own, so the framework does not insist on a record ID it will never use.

Signature: global protected Boolean requiresTriggeringRecord

Default Behavior: true.

When to Set to false:

  • API doesn't need a specific record context (GET requests)
  • Uses only parameters
  • Operates on multiple records
  • Utility/system operation

Example:

apex
public override void configure()
{
	super.configure();
	requestPayload = new DTO_Request();
	responsePayload = new DTO_Response();
	requiresTriggeringRecord = false;
}

Inbound-Specific Methods (API_Inbound) ​

These methods are only available in inbound APIs.


Reading a request header ​

Wrap the headers in kern.UTIL_Map.CaseInsensitiveMap, and the header is found whatever case its name arrived in. You can do this in any of your handler's overrides.

  • HTTP header names carry no case, and many callers (Node and every HTTP/2 client among them) send them in lower case, so a caller may send x-partner-id where you expect X-Partner-Id.
  • request.headers.get(...) finds a header only when its name has exactly the case you asked for.
apex
/**
 * @description Rejects a request that does not name the partner sending it.
 */
public override List<String> getValidationErrors()
{
	List<String> errors = super.getValidationErrors();
	String partner = (String)new kern.UTIL_Map.CaseInsensitiveMap(request.headers).get('X-Partner-Id');

	if(String.isBlank(partner))
	{
		errors.add('The X-Partner-Id header is required');
	}

	return errors;
}

processRequest() ​

Purpose: This is the heart of an inbound endpoint: where you read what the caller sent, look up whatever Salesforce data you need, and run your business logic. The framework hands you the request here and lets you decide what to do with it.

Signature: global protected virtual void processRequest()

Default Behavior: No-op (does nothing).

When to Override:

  • Parse request body
  • Query Salesforce data
  • Perform business logic
  • Validate complex rules

Example:

apex
/**
 * @description Processes incoming request and queries related data.
 */
public override void processRequest()
{
	super.processRequest();

	// Parse request
	DTO_Request request = (DTO_Request)requestPayload;

	// Query related data
	Account account = (Account)QRY_Builder.selectFrom(Account.SObjectType)
		.fields(new List<SObjectField>{Account.Id, Account.Name})
		.condition(Account.ExternalId__c).equals(request.accountId)
		.getFirst();

	// Perform business logic
	if(account != null)
	{
		// Process account
	}
}

updateCallResult() ​

Purpose: Shapes the data that goes into the call result the caller receives. Override it when you want the response formatted a particular way, such as pretty-printed JSON.

Signature: global protected virtual void updateCallResult()

Default Behavior: Sets result.responseBody from responsePayload.

When to Override: When custom response formatting is needed.

Example:

apex
/**
 * @description Formats response as pretty-printed JSON.
 */
public override void updateCallResult()
{
	super.updateCallResult();

	DTO_Response response = (DTO_Response)responsePayload;
	result.responseBody = JSON.serializePretty(response, true);
}

updateResponseDTO() ​

Purpose: Lets you add information to the reply that only exists after records are saved, such as the new record's ID. The framework runs this once the save has finished, so the values are real.

Signature: global protected virtual void updateResponseDTO()

Default Behavior: No-op (does nothing).

When to Override:

  • Include committed record IDs in response
  • Add calculated fields from committed data
  • Include related data from database

Example:

apex
/**
 * @description Updates response with committed Account ID.
 */
public override void updateResponseDTO()
{
	super.updateResponseDTO();

	DTO_Response response = (DTO_Response)responsePayload;
	response.accountId = committedAccount.Id;
	response.timestamp = Datetime.now();
}

writeResponse() ​

Purpose: Sends the final HTTP response back to whoever called your endpoint. Override it when you need to control the exact output: a custom format, a different content type, an error shape, or extra response headers.

Signature: global protected virtual void writeResponse()

Default Behavior: Serializes responsePayload to JSON or writes errors.

When to Override:

  • Custom response formatting
  • Different content types
  • Custom error structures
  • Response headers

Example:

apex
/**
 * @description Writes response with custom headers.
 */
public override void writeResponse()
{
	super.writeResponse();

	// Add custom response headers
	response.setHeader('X-API-Version', '2.0');
	response.setHeader('X-Status-Code', result.statusCode);
}

How does it work? ​

Architecture Diagram ​

The diagram shows which box you write and which boxes the framework already gives you, on each side of a call. Read it top to bottom:

  • a call leaving Salesforce (outbound) starts at your code and ends with an audit record, retry, and circuit breaker;
  • a call arriving at Salesforce (inbound) starts at an HTTP request and ends at your handler.
text
+---------------------------------------------------------------------------+
|                      WEB SERVICES FRAMEWORK ARCHITECTURE                  |
+---------------------------------------------------------------------------+
|                                                                           |
|  OUTBOUND FLOW (Salesforce -> External System)                            |
|  =============================================                            |
|                                                                           |
|  Your Code / Flow / Trigger                                               |
|        |                                                                  |
|        v                                                                  |
|  +-----------------------------+     +-----------------------------+      |
|  |     UTIL_HttpClient         |     |      API_Outbound          |      |
|  |  (Fluent HTTP Client)       |     |  (Full Lifecycle Handler)  |      |
|  |  .post().body().send()      |     |  configure/validate/send   |      |
|  +-------------+---------------+     +-------------+---------------+      |
|                |                                   |                      |
|                +-----------------------------------+                      |
|                                |                                          |
|                                v                                          |
|                  +-----------------------------+                          |
|                  |       API_Dispatcher         |                         |
|                  |  Phase 1: HTTP Callout       |                         |
|                  |  Phase 2: Commit DML         |                         |
|                  +-------------+---------------+                          |
|                                |                                          |
|          +---------------------+---------------------+                    |
|          v                     v                     v                    |
|  +---------------+   +----------------+   +------------------+           |
|  | ApiCall__c    |   | UTIL_Retry     |   | UTIL_Circuit     |           |
|  | (Audit Log)   |   | (Retry Logic)  |   | Breaker          |           |
|  +---------------+   +----------------+   +------------------+           |
|                                                                           |
+---------------------------------------------------------------------------+
|                                                                           |
|  INBOUND FLOW (External System -> Salesforce)                             |
|  =============================================                            |
|                                                                           |
|  HTTP Request                                                             |
|        |                                                                  |
|        v                                                                  |
|  +-----------------------------+     +-----------------------------+      |
|  |  REST_* (@RestResource)     |---->|       API_Dispatcher        |      |
|  |  REST routing only          |     |  processInboundService()    |      |
|  +-----------------------------+     +-------------+---------------+      |
|                                                    |                      |
|                                                    v                      |
|                                      +-----------------------------+      |
|                                      |       API_Inbound           |      |
|                                      |  validate -> onSuccess ->   |      |
|                                      |  updateResponseDTO          |      |
|                                      +-----------------------------+      |
|                                                                           |
+---------------------------------------------------------------------------+
|                                                                           |
|  CONFIGURATION (Custom Metadata)                                          |
|  ===============================                                          |
|  ApiSetting__mdt    - Endpoint, retry, circuit breaker                    |
|                       (outbound: HTTP method via getHttpMethod() override)|
|  ApiCredential__mdt - Named Credential references                         |
|  MaskingRule__mdt   - Shared redaction rules (regex, JSON key, literal)    |
|  MaskingTarget__mdt - Wires rules to specific fields or wildcards          |
|  ApiRuntimeSwitch__c - Emergency kill switch for all APIs                 |
|                                                                           |
+---------------------------------------------------------------------------+

Class Hierarchy ​

You only write the part that is unique to your integration: you extend one of two classes the framework provides, and everything above it is handled for you.

In the tree below, outbound classes (Salesforce calling out) extend API_Outbound, inbound classes (something calling into Salesforce) extend API_Inbound, and both sit under the shared API_Base, so all the call handling lives in one place.

text
API_Base (Abstract Base)
├── API_Outbound
│   ├── API_CallCurrentOrg (for intra-org calls)
│   └── Your Outbound REST APIs (e.g., API_PostExample, API_GetPwndPasswords)
└── API_Inbound
    └── Your Inbound REST APIs (e.g., API_Echo)

Key Design Patterns ​

In plain terms:

  • The base classes run the whole call for you. They only ask your class to fill in the parts that are specific to your integration: the URL, the body, what to do on success.
  • Records you want to save are written together as one all-or-nothing batch: either every record commits, or if anything fails the whole set rolls back.
  • That save happens after the callout finishes, never before it. See Framework Orchestration Pattern for why that ordering matters.

For readers who recognise the patterns by name, here is how those behaviours map to the classic names:

  1. Template Method Pattern: Base classes define the flow; child classes override specific steps
  2. Unit of Work Pattern: Database changes are batched and committed together, registered as a set and saved all-or-nothing
  3. Data Transfer Object (DTO) Pattern: Separate objects for request/response serialization, a small class that holds exactly the fields to move in or out and converts itself to and from JSON
  4. Factory Pattern: Mock objects and API handlers created via factories
  5. Strategy Pattern: Different behaviors for inbound vs outbound
  6. Orchestration Pattern: Callouts execute before DML commits (see Framework Orchestration Pattern and API_Dispatcher)

The Orchestration Pattern Explained ​

API_Dispatcher.execute() enforces the order explained in Framework Orchestration Pattern, in two phases.

Phase 1: Process (Execute HTTP Callouts)

apex
for(ApiCall__c queueRecord : queueRecords)
{
	API_Base apiHandler = getHandler(queueRecord.ServiceName__c);
	apiHandler.process(queueRecord);  // Performs HTTP callout
	handlersToCommit.add(apiHandler);
}

Phase 2: Commit (Persist DML Operations)

apex
for(API_Base handlerToCommit : handlersToCommit)
{
	handlerToCommit.commitWork();  // Commits DML operations
}

Every HTTP callout completes before any DML, which also keeps transactional integrity across multiple APIs.


What are the moving parts? ​

ApiCall__c (Custom Object) ​

Every API call leaves a record here, so when an integration misbehaves in production you have the request, the response, the timing, and the outcome on hand instead of a debug log that has already expired. Key fields:

All ApiCall__c fields
FieldDescription
ServiceName__cAPI class name (e.g., API_PostExample)
Direction__cInbound or Outbound
Status__cQueued, Processing, Completed, Failed, Aborted, Retry, Retrying, Batched
TriggeringRecordId__cThe record that started the call: a record Id, or other text of up to 80 characters, such as an order number from another system. An outbound call takes text that is not a record Id only when its class sets requiresTriggeringRecord to false. Some values of exactly 15 letters and digits, shaped like a short record Id, are read as a record Id
TriggeringRecordIndex__cA copy of TriggeringRecordId__c, exactly as written, kept in a field with a database index for the finders below
Request__cRequest body (auto-truncated if too large)
Response__cResponse body (auto-truncated if too large)
RequestParameters__cJSON serialized parameters
URL__cEndpoint URL
StatusCode__cHTTP status code
ErrorMessages__cError messages if call failed
NextRetry__cScheduled retry datetime (populated when retry is needed)
Retries__cNumber of retry attempts made
IsPermanentFailure__cPermanent Failure: ticked when sending the request again cannot fix the failure, so Retry refuses the call. A UTIL_Exceptions.RequestRefusedException does not tick it
PreviousAttempt__cPrevious Attempt: the earlier call this call is a retry or a replay of. The earlier call lists its retries under Later Attempts
IsMockedResponse__cIndicates if response was mocked
CalloutDurationMs__cTime spent in HTTP callout (milliseconds)
HandlerDurationMs__cTime spent in handler logic
CommitDurationMs__cTime spent committing DML
TotalDurationMs__cTotal end-to-end time
LoggerContext__cSerialized logger context for transaction correlation

Scope: what ApiCall__c does and does not log. It is not an org-wide API-usage log.

  • Logged: callouts that flow through the KernDX Web Services framework: outbound calls via API_Outbound / UTIL_HttpClient / API_Dispatcher, and inbound calls handled by API_Inbound.
  • Never logged: direct Http / HttpRequest callouts, managed-package callouts, and platform API consumption.
  • For org-wide API, login, and limit monitoring, use Salesforce Event Monitoring rather than ApiCall__c.

Large Content Handling: A big payload won't be silently cut off and lost. If request/response bodies exceed field limits, they're stored as ContentVersion files linked to the queue item, so the full body is still kept.

Automatic Transaction Correlation: a queue item the dispatcher runs keeps its user action's correlation ID, with no code changes in your org.

An integration usually runs in the background, after the user's click has finished, and the LoggerContext__c field ties the background logs back to the action that started them. It carries a correlation ID, one tracking ID that follows a single user action across triggers, queries, callouts, and jobs.

  • Captured: when queue items are created via TST_Factory.newOutboundApiCall() or newInboundApiCall(), the current logger context (correlation ID, transaction ID, global context) is automatically captured. A call you build with UTIL_HttpClient stores the same context when you give it a correlation ID with .withCorrelationId().
  • Restored: when API_Dispatcher.execute() processes the queue item asynchronously, it hydrates this context, ensuring all logs in the async transaction share the same correlation ID as the originating transaction.

How do I find the calls made for one record? ​

Say an order page should list the API calls made for that order. Ask the selector for the calls of the order's Id:

apex
List<ApiCall__c> calls = new SEL_ApiCall().findByTriggeringRecordIds(new Set<Id> {orderId}, 25);
List<ApiIssue__c> issues = new SEL_ApiIssue().findByTriggeringRecordIds(new Set<Id> {orderId}, 25);

Both finders search Triggering Record Index (TriggeringRecordIndex__c), a copy of TriggeringRecordId__c that the framework fills on every save. Unlike TriggeringRecordId__c, Triggering Record Index has a database index, so the search uses it instead of reading every row. The Objects & Metadata guide explains when the field is filled and why older rows may have it blank.

Which finder do I use? SEL_ApiCall and SEL_ApiIssue each have both:

FinderUse it forHow it matches
findByTriggeringRecordIds(Set<Id> recordIds, Integer rowLimit)Salesforce record IdsSearches the 18-character form of each Id, which is the form the framework writes. A value stored in the 15-character form is not found.
findByTriggeringRecordValues(Set<String> values, Integer rowLimit)Values that are not record Ids, such as an order number from another systemMatches each value in Triggering Record Index as you write it, but ignores upper and lower case: ORD-1 also finds ord-1.
  • Write the 18-character form. If your code sets TriggeringRecordId__c itself, write String.valueOf(recordId), which gives the 18-character form, so the Id finder finds the row.
  • Do not use the finder by values for 15-character Ids. Two different records can have 15-character Ids that differ only in case, and the finder by values ignores case, so it could return another record's calls.
  • Both finders return at most rowLimit rows, newest first. Rows saved at the same moment are ordered by their own Id, newest first, so the order is the same every time.
  • They refuse bad input. A null set, or a rowLimit that is null or below 1, throws IllegalArgumentException. A null value in the set (and a blank one, for the finder by values) is ignored, and the set you pass is not changed. A set with no usable value returns an empty list and runs no query.
  • They return summary fields only: Id, ServiceName__c, Status__c, CreatedDate and TriggeringRecordIndex__c. They never return the request or the response.
  • To read the request or the response, read that one call by its Id as a separate step, through a selector of your own on kern__ApiCall__c that adds Request__c and Response__c for that one read. For example, call new SEL_ApiCalls().findByIdWithBodies(callId) on the SEL_ApiCalls selector shown under Performance Monitoring, whose other reads leave the bodies out.
  • That read runs in user mode (while the UserModeQueries_Enabled flag is on, as it ships), so a user without access to those fields gets a QueryException, as with the finders. A body too long for its field is kept in a file on the call (see Accessing Large Payloads).
  • A row whose Triggering Record Index is blank is not found. Rows saved before your org's upgrade added the field are blank until you run the optional script in the release note.

What access does the user need? The finders check the running user's access (user mode: the user's object permissions, field permissions and record sharing all apply). Unlike the selectors' other reads, they do not skip these checks. A user who should see a record's calls needs:

  1. Read on the object: API Call, or API Issue for the issue finder.
  2. Read on the fields ServiceName__c, Status__c and TriggeringRecordIndex__c of that object.
  3. Record sharing that shows them the rows. Both objects are private, so a user sees only the rows they own unless a sharing rule, a role above the owner or View All shares the others with them.

What happens when access is missing:

  • No object or field access: the user gets an error (a QueryException), not an empty list.
  • Access, but sharing hides a row: the user does not get that row.

The Kern Administrator and Kern API Issue Resolver permission sets include the object and field access, and both let the user see every row. For your own users, such as order users, grant the access in a permission set of your own and set up the sharing they need.

ApiSetting__mdt (Custom Metadata Type) ​

Each row holds the configuration for one API service, so you tune how each integration behaves (retries, circuit-breaker thresholds, which credential it uses) without changing code:

FieldDescription
ClassName__cAPI class name (must match exactly)
EndpointPath__cAPI endpoint path (appended to Named Credential)
ApiCredential__cLookup to credentials metadata
IsActive__cWhether the API service is active (default: true). Inactive services abort with an error
RequiredFeatureFlag__cMetadataRelationship lookup to FeatureFlag__mdt, required for the service to execute
BypassFeatureFlag__cMetadataRelationship lookup to FeatureFlag__mdt, bypasses the service when enabled
MaxRetryCount__cMaximum retry attempts (e.g., 3)
RetryBackoffSeconds__cSeconds to wait before first retry (e.g., 30). The wait worked out from this value is never longer than 300 seconds unless the handler overrides createRetryStrategy()
CircuitBreakerFailureThreshold__cNumber of consecutive failures before circuit opens (e.g., 5)
CircuitBreakerTimeout__cSeconds to keep circuit open before testing recovery (e.g., 60)
CircuitBreakerSuccessThreshold__cNumber of consecutive successes in half-open state to close the circuit (e.g., 2)
LogIssues__cCreate ApiIssue__c records
ResolveIssues__cAuto-resolve failures on success. Inbound, it also needs IdempotencyEnabled__c and an Idempotency-Key on the request
RetryIssues__cLets Retry, Retry Selected and the Retry API Issues flow action run a failed call again. Inbound, it replays the request in your org
IdempotencyEnabled__cInbound: a repeat of a key from the same user gets the stored answer, and a retry is linked to the failed call. Outbound: sends an Idempotency-Key header

Centralised Validation: Three of these settings decide whether the service is allowed to run at all, so you can turn an integration off, or limit it to a feature flag, from configuration alone. The framework checks these three fields before any handler runs:

  1. IsActive__c: If false, the service aborts with error: "API service is not active"
  2. RequiredFeatureFlag__c: If the Feature Flag is not enabled for the running user, the service aborts with error: "Required condition "{0}" is not met"
  3. BypassFeatureFlag__c: If the Feature Flag is enabled for the running user, the service aborts with error: "API service bypassed by feature flag "{0}""

In the last two messages, the framework puts the name of the feature flag in place of {0}.

These checks run in both inbound and outbound flows, before getValidationErrors() is called.

MaskingRule__mdt + MaskingTarget__mdt ​

Masking (redaction) keeps secrets and personal data out of your logs, so a card number or an auth token in a request body never gets stored in plain text.

The setup is split across two metadata types, so one rule (for example, "find credit card numbers") can be reused against many fields on many objects without copying the pattern into each place.

MaskingRule__mdt: the reusable what to find definition:

FieldDescription
Mode__cRegex, JsonKey (picklist label "JSON by Key"), ExactMatch, or CreditCard (the pattern match plus a Luhn checksum)
Pattern__cRegex pattern, JSON key regex, or literal string (depending on Mode)
Replacement__cReplacement text (e.g., [CARD_REDACTED])
CaseSensitive__cToggle case-insensitive matching
FailureAction__cLogAndContinue, WriteFailureMarker, or BlockDml when a pattern throws
IsActive__cEnable/disable rule globally
MinInputLength__cOptional minimum input length, rule skipped for values shorter than this (zero-cost short-circuit for short fields like URLs); a JsonKey rule ignores it
ApplicableFieldTypes__cOptional semicolon-delimited System.DisplayType.name() list (e.g., STRING;TEXTAREA;ENCRYPTEDSTRING) restricting the rule to specific field types; blank applies to every text-shaped field

MaskingTarget__mdt: the wiring that points a rule at the fields it should run on:

FieldDescription
Rule__cThe MaskingRule__mdt to apply
SObjectType__cTarget SObject (e.g., ApiCall__c)
Field__cSpecific field path, or blank for a wildcard across every text field (unique keys and external ids excepted)
CallerClass__cOptional: one service's API calls and API issues only (see below)
IsActive__cEnable/disable this wiring without touching the rule

Default ship set (3 rules active, 14 targets, 10 of them switched on): Sensible protection is already on the day you install, so common secrets are masked before you configure anything. Three rules do the work out of the box:

RuleWhat it findsLimitsWildcarded onto
MaskSecretKeysJSON key redaction for password/token/apiKey/authorization/bearer and similarScoped to STRING;TEXTAREA, since JSON payloads only live in free-text fieldsApiCall__c, ApiIssue__c, AsyncChainExecution__c, and LogEntryEvent__e
MaskPaymentCardCreditCard mode: 13-19 digit sequences passing the Luhn checksum, spaces or hyphens allowedMinInputLength = 13, restricted to STRING;TEXTAREA;ENCRYPTEDSTRING field typesThe same four objects
MaskJwtJSON Web Tokens: a token that starts with eyJ and has three dot-separated partsMinInputLength = 20ApiCall__c and ApiIssue__c
  • MaskPaymentCard replaces the original MaskCreditCard rule, which ships switched off, and so do its own four targets. If you switch it on, switch its four targets on with it. Where both rules are wired to the same object, the payment-card rule does the work.
  • Fourteen other rules ship as inactive templates: SSN, IBAN, SWIFT/BIC, MBI, health keywords, email, US phone, AWS access key, URL basic auth, authorization header, private IPv4, postal address, free text, and international phone. When your org's data profile calls for one, flip IsActive__c = true and add a MaskingTarget__mdt to switch it on.

Rule-level filters override explicit target wiring. The rule's own field-type filter wins over what the target asks for, so know this before you debug a mask that never fires.

  • The case: a MaskingTarget__mdt wires a rule to a specific Field__c (non-wildcard) whose DisplayType is excluded by the rule's ApplicableFieldTypes__c. The rule will not fire on that field.
  • How you catch it: the framework emits a one-time warn-level LogEntry__c with ClassMethod__c = 'UTIL_FrameworkMasker.filterTargetsByFieldType', surfacing the misconfiguration.
  • The fix: either widen the rule's ApplicableFieldTypes__c to include the field's type, or remove the target.
  • MinInputLength__c behaves similarly but is a value-length check at mask time. It does not warn, so be careful: a rule whose minimum exceeds the field's schema max length will silently never fire.

ApiRuntimeSwitch__c (Hierarchy Custom Setting) ​

This is the kill switch: a master off-switch you can flip without a deployment when an integration is causing harm in production. It disables all APIs at the org, profile, or user level, so you can stop the bleeding in seconds and investigate afterwards.

FieldDescription
DisableAllApis__cDisable all APIs (inbound and outbound)

That switch is deliberately broad. To turn off just one service instead of everything, use ApiSetting__mdt.IsActive__c. To disable APIs through a feature flag (UTIL_FeatureFlag), use the DisableAllAPIs flag.

To make services answer mock data instead, use one of these feature flags (see Declarative Mock Mode):

  • the MockAllAPIs flag, for every outgoing service;
  • the MockAllInboundAPIs flag, for every incoming service;
  • the MockSelectedAPIs flag, for only the services whose API Setting has Mocking Enabled ticked, in both directions.

Named Credentials ​

Your endpoint URLs and passwords live here, kept out of code so a credential rotation never means a redeploy. A Named Credential stores the authentication details securely via External Credentials, and ApiSetting__mdt points to it by name.

An API that wants its key in a header keeps the key in an External Credential too: see Where credentials belong.

A server signed by your own certificate authority. A Named Credential can also reach a server whose certificate is signed by your own private or internal certificate authority:

  • Where: Winter '27 and later, in Enterprise, Performance, Unlimited and Developer editions, though not in every org.
  • How: upload the issuing root certificate to your org's certificate trust store, and named credential callouts to that endpoint trust it from then on.
  • Without the upload: the TLS handshake happens before any token or API key is sent, so a callout to such a server fails before the request leaves your org, whatever authentication the credential carries.

An internal service behind a corporate certificate authority therefore needs no publicly trusted certificate to be called through kern.UTIL_HttpClient.

The two named credentials KernDX ships. Both back the framework's outbound examples and call public, unauthenticated endpoints, so they store no secrets:

Named CredentialLabelEndpointAuthenticationUsed by
API_ExampleRestApiExample REST APIhttps://jsonplaceholder.typicode.comAnonymous (none)The outbound REST example API_PostExample
API_PwndPasswordsPwnd Passwordshttps://api.pwnedpasswords.comAnonymous (none)The breach-check example API_GetPwndPasswords

Replace or remove these when you wire up your own integrations. They are demonstrations, not production endpoints.

The framework does not keep an inventory of your org's named credentials and how critical each one is. That is org configuration, so use native Setup or a posture tool such as AppOmni for it. A managed package does not catalogue your credentials for you.


Anti-Patterns ​

Each habit quietly breaks something the framework was built to give you: a searchable record of every call, automatic retries, hidden sensitive data, testability, or a callout that runs in the right order.

Anti-PatternWhy It's WrongInstead
Raw HttpRequest/HttpResponse without the frameworkNo logging, no retry, no data masking, no mock supportExtend API_Outbound or API_Inbound and let the orchestrator handle the lifecycle
DML before callout in the same transactionSalesforce throws CalloutException; you cannot make callouts after DMLUse the framework's orchestration pattern: callout first, then onSuccess() for DML registration
Hardcoding endpoints or credentials in ApexCannot change per environment, fails security review, blocks testingUse ApiSetting__mdt + Named Credentials; override getWebServiceEndPoint() only when dynamic
Overriding every virtual methodMakes the class brittle and harder to maintain when the framework evolvesOverride only what differs from the defaults (see Override Only What You Need)
Skipping @JsonAccess on DTOs in your orgSerialisation fails at runtime with a security error in managed package contextAlways add @JsonAccess(serializable='always' deserializable='always') to every DTO

Best Practices ​

Code Standards ​

Follow these conventions so your code matches the rest; when everyone writes integrations the same way, any developer can read and maintain any of them:

  • Use tabs for indentation (indent size: 3, tab size: 3)
  • Braces on new lines (Allman style)
  • No space before control structure parentheses
  • Keywords (else, while, catch) on new lines
  • ApexDoc for all public/global methods and classes
  • Meaningful variable names in camelCase

Naming Conventions ​

Use these prefixes. Consistent class names make it obvious at a glance what each class does and which direction it points, so you spend less time hunting through code:

Outbound APIs:

  • REST: API_Get*, API_Post*, API_Put*, API_Patch*, API_Delete*
  • Intra-Org: API_* (extends API_CallCurrentOrg)
  • Mocks: API_*Mock

Inbound APIs (Two-Class Pattern):

  • REST Routing Classes: REST_*
    • Examples: REST_Echo, REST_Person, REST_Invoices
  • API Implementation Classes: API_*
    • Examples: API_Echo, API_PersonRetrieve, API_PersonUpdate

Common:

  • DTOs: DTO_Request, DTO_Response, DTO_* (nested)

Override Only What You Need ​

Only override a method when you actually need to change its default: the base class already sets a default for most settings. Your class stays short and the parts you did change stand out:

apex
// ❌ BAD - Unnecessary overrides
public override String getEncoding()
{
	return HTTP_ENCODING_JSON;  // Already the default!
}

public override HttpMethod getHttpMethod()
{
	return HttpMethod.POST;  // Already the default!
}

// ✅ GOOD - Only override when changing defaults
public override HttpMethod getHttpMethod()
{
	return HttpMethod.GET;  // Different from default
}

Error Handling ​

When you need to react to a failure (alert an admin, log to another system, open a follow-up case), override handleError and call super.handleError(error) first so the framework's own error handling still runs. Then add your extra steps:

apex
/**
 * @description Handles errors with custom notification logic.
 *
 * @param error The exception that occurred
 */
public override void handleError(Exception error)
{
	super.handleError(error);

	// Send notification to administrators
	// Log to external system
	// Create case for follow-up
}

Logging Best Practices ​

Good logs are what let you investigate a failure after it happens, without leaking anything you shouldn't. Three habits cover most cases:

  • Always use the LOG_Builder fluent API (configure the entry with short chained calls, then one call emits it) for application errors:

    apex
    LOG_Builder.build().error(error).emitAt('API_PostExample.prepareRequest');
  • Don't log sensitive data. Use data masks instead, so secrets and personal data never land in your logs.

  • Use the right log level so urgent problems stand out from routine noise:

    • LOG_Builder.build().error().emitAt() - Errors requiring attention
    • LOG_Builder.build().warn().emitAt() - Potential issues
    • LOG_Builder.build().info().emitAt() - Informational messages
    • LOG_Builder.build().debug().emitAt() - Detailed debugging (disabled in prod)

Security Considerations ​

A few habits keep integrations safe by default and out of the headlines:

  • Never hardcode credentials. Use Named Credentials, so secrets live in secure configuration, not in your source.
  • Validate all inputs in getValidationErrors(), so bad or malicious data is rejected before it reaches your logic.
  • Use HTTPS for all external endpoints.
  • Mask sensitive fields, so personal data and secrets stay out of your logs.
  • Choose the right sharing model (with sharing vs without sharing) so each integration sees only the records it should.

Performance Optimization ​

These habits keep integrations fast and clear of governor limits as data volumes grow:

  • Use asynchronous callouts for long-running operations.
  • Batch multiple API calls when possible, so you make fewer round trips.
  • Add pagination for large result sets.
  • Set sensible timeouts, so a slow endpoint fails fast instead of hanging.
  • Avoid SOQL in loops in prepareRequest(), so you don't exhaust query limits.

Understanding the Orchestration ​

The framework runs callouts first and saves afterwards (Framework Orchestration Pattern). Because of that order, you should:

  • Never call DML directly in process() method
  • Always use doInsert(), doUpdate(), doDelete() within onSuccess()
  • Let the framework handle commit timing

Troubleshooting ​

Common Issues ​

Status code is 0 ​

Symptom: send() returns a response whose status code is 0

Possible Causes:

  • The call was stopped before it left your org: a credential that could not be resolved, an open circuit breaker, or a refusal from validation
  • The call went out and nothing came back: a timeout or a transport failure

Solutions:

  • Read getStatus() on the response for the reason, when one was recorded (What a response tells you)
  • Check whether the call is retried later (Failures and retries):
    • a call that went out and got no answer is retried only when the request is safe to repeat;
    • a call stopped by an open circuit breaker is tried again after the breaker's cool-off while retries remain, whatever the method;
    • a call the platform refused before it left your org is tried again while retries remain, whatever the method;
    • a refusal from validation ends the call Aborted (Custom Retry Strategies).

API Call is Aborted ​

Symptom: Queue item shows Status__c = 'Aborted'

Possible Causes:

  • API disabled via feature flag or ApiRuntimeSwitch__c
  • Missing required parameters
  • Missing ApiSetting__mdt record
  • No triggering object when required

Solutions:

  • Check ErrorMessages__c field for specific error
  • Verify ApiRuntimeSwitch__c and feature flag settings
  • Confirm ApiSetting__mdt exists with correct ClassName__c
  • Provide required parameters

Namespace Errors ​

Symptom: "Type cannot be constructed: API_Outbound"

Possible Cause: You left off the namespace prefix in a managed package context, so the base class can't be found.

The same code snippet also trips a second, separate framework convention: every Apex class must declare its sharing mode (with sharing, inherited sharing, or without sharing). Both rules apply independently, so fix both at once.

Solution:

apex
// ❌ WRONG — missing sharing modifier AND namespace prefix (both required in your org)
public class MyAPI extends API_Outbound
{
}

// ✅ CORRECT — explicit sharing modifier AND namespace-prefixed base class
public inherited sharing class MyAPI extends kern.API_Outbound
{
}

Callout Not Executing ​

Symptom: No HTTP callout occurring

Possible Causes:

Solutions:

  • Check IsMockedResponse__c field
  • Verify the MockAllAPIs feature flag is off for the user the call runs as (this flag turns on mock mode for every outgoing call)
  • If the service's API Setting has MockingEnabled__c ticked, verify the MockSelectedAPIs feature flag is off for that user too; Health Check's Selected API Mocking row lists every active service with the box ticked
  • Ensure Named Credential exists and is accessible

Database Changes Not Committing ​

Symptom: Records not saved despite successful API call

Possible Causes:

  • Not calling doInsert() / doUpdate() within onSuccess()
  • Calling DML directly instead of using framework
  • Exception during commit

Solutions:

  • Use doInsert(), doUpdate(), doDelete() within onSuccess() instead of direct DML
  • Check debug logs for commit errors
  • Verify object permissions (CRUD/FLS: CRUD is the object create, read, update and delete permissions; FLS is field-level security)

Callout from Triggers Error ​

Symptom: "Callout from triggers with uncommitted work pending is not allowed"

Possible Cause: Attempting to make callout with uncommitted DML

Solution: The framework already handles this for you. Make sure you're going through API_Dispatcher.execute(), which runs the callouts before saving any records, so the uncommitted-work error never fires.


Support and Resources ​

Code Examples in Framework ​

The framework ships with example API classes you can read and adapt. Each one shows a different direction and complexity, so you can find the closest match to what you are building:

  • API_Echo - Simple inbound example
  • API_PostExample - Outbound POST with DTOs
  • API_GetPwndPasswords - Outbound GET with parameters
  • API_CallCurrentOrg - Intra-org API base class

These three are not in the package. They are illustrative code written out in full in this guide, for you to copy and adapt:

  • API_SendMail - Complex outbound with nested DTOs
  • API_PersonRetrieve - Inbound GET with validation
  • API_PersonUpdate - Inbound PATCH with DML

Getting Help ​

When an integration misbehaves, the evidence is usually already captured for you. Work through these in order:

  • Check debug logs for detailed error messages
  • Review ApiCall__c records for request/response details, so you can see exactly what was sent and what came back
  • Search for similar patterns in existing API classes
  • Consult with the platform team

  • Logging - Guide - Automatic API logging, correlation tracking, and performance monitoring
  • Triggers - Guide - Trigger-based API callout orchestration via API_Dispatcher
  • DML - Guide - Unit of Work pattern used in onSuccess()
  • Selectors - Guide - Query patterns for DTO population and validation
  • Validation - Guide - Input validation patterns via getValidationErrors()
  • UTIL_HttpClient - Fluent HTTP client for ad-hoc calls with automatic retry, logging, and circuit breaker