Skip to content

API_Outbound ​

Class · Group: Web Services

Learn it: Fast Start - Outbound APIs and Web Services guide

apex
global virtual inherited sharing class API_Outbound extends API_Base

Extends: API_Base

Known Derived Types: API_CallCurrentOrg

Base class for all outbound web service calls. Extends API_Base to provide functionality for making HTTP callouts, handling responses, managing retries, and token replacements.

Example

apex
public with sharing class API_SendEmail extends API_Outbound
{
    public override void configure()
    {
        super.configure();
        requestPayload = new DTO_Request();
        responsePayload = new DTO_Response();
        defaultMockBody = '{"messageId": "msg-12345"}';
    }
}

Methods by task ​

Find a method by what you want to do. A group links to a worked example when a guide has one. Every method is described in the full list below.

GroupMethodsWorked example
Gather the data before the callconfigure getRequiredInputs prepareRequestMinimal Implementation, Complete Real-World Example: REST POST with DML
Shape the requestcreateRequest getAuthorisationToken getBody getEncoding getHttpMethod getQueryParameters getRequestReplacementTokens getTimeout getWebServiceEndPoint setHeadersOutbound-Specific Methods (API_Outbound)
Read the answergetResponseBody getResponseReplacementTokens hasArrayResponse parseResponsegetResponseBody(), getResponseReplacementTokens()
Retry a failed callcreateRetryStrategy getRetryableExceptionTypes getRetryableStatusCodesCustom Retry Strategies, Failures and retries
Switch the call offisDisabledDisabling APIs
Run your own code when the save starts or endsonCommitWorkStarting

Methods ​

MethodDescription
global override virtual void configure()Initializes global variables; override in descendant classes if needed.
global virtual HttpRequest createRequest(String requestBody)Constructs the HttpRequest object used to make the outbound API call.
global virtual UTIL_Retry.Strategy createRetryStrategy()Creates the retry strategy for a failed call.
global virtual String getAuthorisationToken()Returns the authorization token required for outbound API requests.
global virtual override String getBody()Generates the request body using the type of the requestPayload.
global override virtual String getEncoding()Retrieves the HTTP encoding.
global override virtual API_Base.HttpMethod getHttpMethod()Retrieves the HTTP method used for making the outbound request.
global virtual String getQueryParameters()Retrieves relevant query parameters.
global virtual void getRequestReplacementTokens(List<String> searchTokens, List<String> replaceTokens)Specifies token replacements for the request body before serialization.
global virtual Set<String> getRequiredInputs()Indicates required service inputs.
global virtual String getResponseBody()Retrieves the current response body; override to manipulate response body first.
global virtual void getResponseReplacementTokens(List<String> searchTokens, List<String> replaceTokens)Specifies token replacements for the response body before deserialization.
global virtual Set<Type> getRetryableExceptionTypes()The exception types from your own code that the framework may retry.
global virtual Set<Integer> getRetryableStatusCodes()The HTTP status codes the framework may retry when the external system responds with one of them.
global virtual Integer getTimeout()Retrieves the HTTP Service Timeout.
global virtual String getWebServiceEndPoint()Constructs and returns the full URL endpoint for the web service, resolving Named Credentials and appending the API path.
global virtual Boolean hasArrayResponse()Checks if the JSON response is in the form of an array without a key.
global override Boolean isDisabled()Checks whether the API has been disabled for the current user by verifying custom settings or feature switches.
global override virtual void onCommitWorkStarting()Performs actions before the framework saves the call's changes to the database.
global virtual void parseResponse()Called if request is successful; override to consume response.
global virtual void prepareRequest()Prepares the outbound request by querying Salesforce data and populating the request DTO.
global virtual void setHeaders()Sets the HTTP headers for the request.

configure ​

apex
global override virtual void configure()

Initializes global variables; override in descendant classes if needed.

Example

apex
global override void configure()
{
    super.configure();
    requestPayload = new DTO_Request();
    responsePayload = new DTO_Response();
    defaultMockBody = '{"messageId": "msg-12345"}';
}

createRequest ​

apex
global virtual HttpRequest createRequest(String requestBody)

Constructs the HttpRequest object used to make the outbound API call. It sets the headers, request body, and endpoint URL. The request this method returns is the one sent, and whether a failed call is safe to send again is judged from its method and headers: a GET, PUT or DELETE, or a request that carries an Idempotency-Key header, is safe to repeat, and a POST or PATCH that drops the header (for example a new request your override builds without copying it) is treated as not safe to repeat, even when Idempotency Enabled is on or the call has a key. A key your override sets on the request itself counts as sent, and the key recorded on the call and its issue is the one the request carried.

Parameters

ParameterTypeDescription
requestBodyStringThe body content of the request.

Returns HttpRequest — The fully configured request object.

Example

apex
global override HttpRequest createRequest(String requestBody)
{
    HttpRequest httpRequest = super.createRequest(requestBody);
    // customize request
    return httpRequest;
}

createRetryStrategy ​

apex
global virtual UTIL_Retry.Strategy createRetryStrategy()

Creates the retry strategy for a failed call. Override it to give a handler its own backoff, or to refuse a retry the framework would otherwise allow. It runs once for each failed call, after the response has arrived (or after the failure, when there was no response). It runs on the same handler instance that ran prepareRequest(), parseResponse() and onSuccess(), so you may read response, result.statusCode and result.responseBody, and result.errors holds the failure text. The context the strategy receives carries the retry count. When the failure was an exception (a parse failure, a throw from your own code, or a callout that got no response), the context carries that exception too. A failure by status carries no exception, so an allowlist does not stop it and a denylist cannot match it: use getRetryableStatusCodes() for statuses. To refuse the retry, return a strategy whose shouldRetry returns false (UTIL_Retry.linear().withMaxRetries(0)), or throw UTIL_Exceptions.PermanentFailureException. Any other throw ends the call Failed with a warning in the log. The framework decides first, from where the failure happened. The strategy is asked only about a failure the framework may retry.

The default strategy reads the service setting: Retry Backoff Seconds is the base wait, and Max Retry Count is the number of retries. A call made through UTIL_HttpClient with withRetry or withExponentialBackoff uses the number of retries passed there, and the base wait when one was passed, instead of the setting's values, on every run.

It waits the base before the first scheduled retry, and then the base times the number of retries already made, up to 300 seconds. For a base of 120 seconds that is 120, 120, 240 and then 300 seconds.

A call made with withExponentialBackoff gets a different wait: the base before the first retry, then twice as long each time, also up to 300 seconds. For a base of 30 seconds that is 30, 60, 120, 240 and then 300 seconds.

The wait worked out from the base is never longer than 300 seconds, so a Retry Backoff Seconds above 300 has the same effect as 300. While the circuit breaker is open, the retry waits for the cool-off when that is longer. The retries already made count, including the ones sent again at once in the same transaction. This also holds for your handler when it is called through UTIL_HttpClient.useHandler, unless your handler overrides this method: then your strategy decides.

To wait longer than 300 seconds, override this method and set the maximum wait yourself with withMaximumBackoff. The example below declares the method global override because its class is global. In a public class, declare it public override: a global method compiles only inside a global class.

Returns UTIL_Retry.Strategy — Configured instance

Example

apex
global class API_PaymentGateway extends API_Outbound
{
    global override UTIL_Retry.Strategy createRetryStrategy()
    {
        return UTIL_Retry.exponential()
            .withBaseBackoff(5)
            .withMaxRetries(3);
    }
}

getAuthorisationToken ​

apex
global virtual String getAuthorisationToken()

Returns the authorization token required for outbound API requests.

Returns String — The authorization token to be used in the Authorization HTTP header.

Example

apex
global override String getAuthorisationToken()
{
    return 'Bearer ' + accessToken;
}

getBody ​

apex
global virtual override String getBody()

Generates the request body using the type of the requestPayload. Applies token replacements to the request body before sending.

Returns String — The serialized request body.

Example

apex
global override String getBody()
{
    return JSON.serialize(customPayload);
}

See Also DTO_Base

getEncoding ​

apex
global override virtual String getEncoding()

Retrieves the HTTP encoding.

Returns String — The HTTP encoding, defaults to JSON.

Example

apex
global override String getEncoding()
{
    return 'application/xml';
}

getHttpMethod ​

apex
global override virtual API_Base.HttpMethod getHttpMethod()

Retrieves the HTTP method used for making the outbound request.

Returns API_Base.HttpMethod — The HTTP method to be used. Defaults to POST if not provided by the superclass.

Example

apex
global override HttpMethod getHttpMethod()
{
    return HttpMethod.GET;
}

getQueryParameters ​

apex
global virtual String getQueryParameters()

Retrieves relevant query parameters.

Returns String — A list of query parameters.

Example

apex
global override String getQueryParameters()
{
    return 'key=' + EncodingUtil.urlEncode(value, 'UTF-8');
}

getRequestReplacementTokens ​

apex
global virtual void getRequestReplacementTokens(List<String> searchTokens, List<String> replaceTokens)

Specifies token replacements for the request body before serialization. Override to replace reserved words or tokens in the request body before sending.

Parameters

ParameterTypeDescription
searchTokensListThe list of search tokens to look for in the request body.
replaceTokensStringThe list of replacement tokens to use if matching search tokens are found.

Example

apex
global override void getRequestReplacementTokens(List<String> searchTokens, List<String> replaceTokens)
{
    searchTokens.add('{TODAY}');
    replaceTokens.add(String.valueOf(Date.today()));
}

getRequiredInputs ​

apex
global virtual Set<String> getRequiredInputs()

Indicates required service inputs.

Returns String — A set of required service input names.

Example

apex
global override Set<String> getRequiredInputs()
{
    Set<String> requiredInputs = super.getRequiredInputs();
    requiredInputs.add(PARAM_RECIPIENT);
    return requiredInputs;
}

getResponseBody ​

apex
global virtual String getResponseBody()

Retrieves the current response body; override to manipulate response body first. Automatically wraps array responses and applies token replacements.

Returns String — The response that will be parsed.

Example

apex
global override String getResponseBody()
{
    String body = super.getResponseBody();
    // manipulate response body before parsing
    return body;
}

getResponseReplacementTokens ​

apex
global virtual void getResponseReplacementTokens(List<String> searchTokens, List<String> replaceTokens)

Specifies token replacements for the response body before deserialization. Override to replace reserved words or tokens in the response before processing.

Parameters

ParameterTypeDescription
searchTokensListThe list of search tokens to look for in the response body.
replaceTokensStringThe list of replacement tokens to use if matching search tokens are found.

Example

apex
global override void getResponseReplacementTokens(List<String> searchTokens, List<String> replaceTokens)
{
    searchTokens.add('currency');
    replaceTokens.add('currencyIsoCode');
}

getRetryableExceptionTypes ​

apex
global virtual Set<Type> getRetryableExceptionTypes()

The exception types from your own code that the framework may retry. By default none: code that ran in your org and threw fails the same way on every attempt, so the call ends Failed at once with one issue. List a type here when a failure of that type can pass on its own, for example a row lock in a selector. A type is matched by its exact name; list each concrete type you throw, because a parent type such as Exception matches nothing. After a successful response the framework retries a listed type only when the request is safe to repeat: GET, PUT, DELETE, or an Idempotency-Key was sent. A callout that got no response retries on a safe-to-repeat request without being listed here; listing System.CalloutException retries it on a POST without an Idempotency-Key too, at your own risk.

Returns Type — The exception types a retry may follow; empty by default.

Example

apex
global override Set<Type> getRetryableExceptionTypes()
{
    return new Set<Type> {System.QueryException.class};
}

getRetryableStatusCodes ​

apex
global virtual Set<Integer> getRetryableStatusCodes()

The HTTP status codes the framework may retry when the external system responds with one of them. The default is 408, 425, 429, 500, 502, 503 and 504. Any other status ends the call Failed at once. A 408, 425, 429 or 503 means the external system did not process the request, so it is retried for every request. A 500, 502 or 504 can come after the external system processed the request, so it is retried only when the request is safe to repeat: a GET, PUT or DELETE, or a request that sent an Idempotency-Key. A POST or PATCH without a key that gets one of those three ends Failed at once, and its issue says the external system may have acted. Override this method to add a code your external system uses to mean "try later", or to remove one. An empty set, or null, retries no status. A code you add that is not in the default list is your own choice, so it is retried for every request, whatever its method. Adding it does not change how 500, 502 and 504 are treated. This method does for a handler what UTIL_HttpClient's retryOn(...) does for a call built with UTIL_HttpClient, with one difference: a 500, 502 or 504 you name in retryOn is retried whatever the method, while one returned here is not. A callout the platform refused before it left your org (for example because unsaved work was pending) has no status, so this method does not decide it. Nothing was sent, so it is tried again while retries remain, whatever the HTTP method.

Returns Integer — The status codes a retry may follow.

Example

apex
global override Set<Integer> getRetryableStatusCodes()
{
    Set<Integer> codes = super.getRetryableStatusCodes();
    codes.add(409);
    return codes;
}

getTimeout ​

apex
global virtual Integer getTimeout()

Retrieves the HTTP Service Timeout.

Returns Integer — The timeout value in milliseconds, defaults to 120000.

Example

apex
global override Integer getTimeout()
{
    return 60000;
}

getWebServiceEndPoint ​

apex
global virtual String getWebServiceEndPoint()

Constructs and returns the full URL endpoint for the web service, resolving Named Credentials and appending the API path.

Returns String — The full URL endpoint for the web service.

Example

apex
global override String getWebServiceEndPoint()
{
    return super.getWebServiceEndPoint() + '/custom-path';
}

hasArrayResponse ​

apex
global virtual Boolean hasArrayResponse()

Checks if the JSON response is in the form of an array without a key. Salesforce DTO classes cannot parse arrays directly, so this method helps handle responses that are arrays.

Returns Boolean — Boolean indicating if the response is an array.

Example

apex
global override Boolean hasArrayResponse()
{
    return true;
}

isDisabled ​

apex
global override Boolean isDisabled()

Checks whether the API has been disabled for the current user by verifying custom settings or feature switches.

Returns Boolean — True if the API is disabled, false otherwise.

Example

apex
global override Boolean isDisabled()
{
    return super.isDisabled() || customDisableCheck();
}

onCommitWorkStarting ​

apex
global override virtual void onCommitWorkStarting()

Performs actions before the framework saves the call's changes to the database. It runs once for each attempt of the save: an attempt the platform refused for a row lock is tried again once, and this method runs again for the new attempt. So write what you add here so that it is safe to run more than once. Always call super.onCommitWorkStarting() first: it prepares the save and the logging for the call.

Example

apex
global override void onCommitWorkStarting()
{
    super.onCommitWorkStarting();
    // work to do before the save
}

parseResponse ​

apex
global virtual void parseResponse()

Called if request is successful; override to consume response.

Example

apex
global override void parseResponse()
{
    super.parseResponse();
    DTO_Response dto = (DTO_Response)responsePayload;
    // process the response
}

prepareRequest ​

apex
global virtual void prepareRequest()

Prepares the outbound request by querying Salesforce data and populating the request DTO.

The request DTO gets the call's Triggering Record ID as a record Id. When that value is not a record Id, such as an order number from another system, the DTO gets null instead. Your code can read the text itself from apiCall.TriggeringRecordId__c.

Some values of exactly 15 letters and digits are accepted as a record Id in its short form, even when they are codes from another system. The DTO then gets the value as a record Id.

Example

apex
global override void prepareRequest()
{
    super.prepareRequest();
    // additional request preparation
}

setHeaders ​

apex
global virtual void setHeaders()

Sets the HTTP headers for the request. Includes Accept header for JSON responses. Override in child classes to add additional service-specific headers.

Example

apex
global override void setHeaders()
{
    super.setHeaders();
    request.setHeader('Custom-Header', 'CustomValue');
}

Properties ​

PropertyDescription
global String baseUrlReturns the base URL of the web service.
global String defaultMockBodyDefault mock response body for unit tests and mock mode.
global HttpRequest requestThe request object used by the API handler to make an outbound call.
global DTO_Base requestPayloadThe DTO that should be serialized for the request body in outbound service calls.
global HttpResponse responseThe response object containing the results of the HTTP callout.
global DTO_Base responsePayloadThe DTO that will deserialize the response body of the external web service call.

baseUrl ​

apex
global String baseUrl

Type: String

Returns the base URL of the web service. This resolves Named Credentials to handle secure credential management in Salesforce.

defaultMockBody ​

apex
global String defaultMockBody

Type: String

Default mock response body for unit tests and mock mode. Set this in configure() to declare the handler's default mock response. When set, the callout mock registered for the service through API_MockFactory.forService uses this as fallback when no factory mock is registered.

request ​

apex
@TestVisible global HttpRequest request

Type: HttpRequest

The request object used by the API handler to make an outbound call. The HttpRequest object is initialized lazily when it's first accessed.

See Also: HttpRequest

requestPayload ​

apex
global DTO_Base requestPayload

Type: DTO_Base

The DTO that should be serialized for the request body in outbound service calls. This object contains the data that will be sent to the external service as part of the HTTP request.

response ​

apex
@TestVisible global HttpResponse response

Type: HttpResponse

The response object containing the results of the HTTP callout. This object is populated after the HTTP call is executed.

See Also: HttpResponse

responsePayload ​

apex
@TestVisible global DTO_Base responsePayload

Type: DTO_Base

The DTO that will deserialize the response body of the external web service call. This object will be populated with the response data after the HTTP call completes.

Fields ​

FieldDescription
global Boolean requiresTriggeringRecordWhether this service requires a triggering object ID.

requiresTriggeringRecord ​

apex
global Boolean requiresTriggeringRecord

Type: Boolean

Whether this service requires a triggering object ID. Override in configure() to set to false for services that don't require a triggering record.

Example

apex
global override void configure()
{
    super.configure();
    requiresTriggeringRecord = false;
}