Sub topic 14
Building a custom adapter with the Apex Connector Framework
The OData and cross-org adapters cover many systems. Some systems speak neither protocol. Others need logic the standard adapters can't express, such as calling a proprietary REST API, merging two backends, or reshaping data. For those cases, the Apex Connector Framework lets you write the adapter yourself in Apex. Salesforce Connect still handles external objects, tabs, layouts, list views, and relationships. Your code only replaces the part that talks to the external system.
This chapter assumes you know basic Apex syntax (classes, methods, collections, overrides) and have read the earlier chapters on external data sources, Validate and Sync, and querying external objects.
When a custom adapter is the right choice
Write a custom adapter when all of these hold:
- The external system has no OData 2.0 or 4.0 endpoint, and putting an OData facade in front of it is not practical.
- You still want live data and not a copy.
- You can accept that your Apex code owns the callout, the parsing, and the error handling.
If an OData endpoint exists, use the OData adapter instead. A custom adapter is code you have to test, deploy, and maintain.
The two classes you write
A custom adapter is two Apex classes that extend two framework base classes.
| Class | Extends | Job |
|---|---|---|
| Provider | `DataSource.Provider` | Declares which authentication methods and capabilities the adapter supports, and returns a connection |
| Connection | `DataSource.Connection` | Describes the external schema in `sync()`, returns rows from `query()`, and optionally handles `search()`, `upsertRows()`, and `deleteRows()` |
Both classes and their overridden methods are declared global, because the framework base classes are global.
The provider class
The provider answers two questions: how does Salesforce authenticate to the system, and what can the adapter do?
global class SampleDataSourceProvider extends DataSource.Provider {
override global List<DataSource.AuthenticationCapability> getAuthenticationCapabilities() {
return new List<DataSource.AuthenticationCapability>{
DataSource.AuthenticationCapability.ANONYMOUS
};
}
override global List<DataSource.Capability> getCapabilities() {
return new List<DataSource.Capability>{
DataSource.Capability.ROW_QUERY
};
}
override global DataSource.Connection getConnection(DataSource.ConnectionParams connectionParams) {
return new SampleDataSourceConnection(connectionParams);
}
}The capabilities list controls what Salesforce lets users do with the resulting external objects:
ROW_QUERYallows reads through SOQL and the UI. A read-only adapter needs only this.SEARCHallows global search to call yoursearch()method.ROW_CREATE,ROW_UPDATE, andROW_DELETEallow writes. They require you to implementupsertRows()anddeleteRows()on the connection.
The authentication capabilities include ANONYMOUS, BASIC, CERTIFICATE, and OAUTH. These determine which identity types the external data source offers in Setup. If the external system needs credentials, don't hard-code them in Apex. Use a named credential and make the callout to the callout: URL for it, as covered in the authentication chapter.
The connection class and the schema
The connection class does the work. Its constructor receives the connection parameters, which carry the endpoint and authentication details configured on the external data source.
global class SampleDataSourceConnection extends DataSource.Connection {
global SampleDataSourceConnection(DataSource.ConnectionParams connectionParams) {
}
override global List<DataSource.Table> sync() {
List<DataSource.Column> columns = new List<DataSource.Column>();
columns.add(DataSource.Column.text('ExternalId', 255));
columns.add(DataSource.Column.url('DisplayUrl'));
columns.add(DataSource.Column.text('Name', 255));
List<DataSource.Table> tables = new List<DataSource.Table>();
tables.add(DataSource.Table.get('Sample', 'Name', columns));
return tables;
}
override global DataSource.TableResult query(DataSource.QueryContext context) {
List<Map<String, Object>> rows = new List<Map<String, Object>>();
rows.add(new Map<String, Object>{
'ExternalId' => '1',
'DisplayUrl' => 'https://example.com/items/1',
'Name' => 'First item'
});
return DataSource.QueryUtils.process(context, rows);
}
}sync(): describing the schema
sync() runs when an admin clicks Validate and Sync on the external data source. It returns a list of DataSource.Table objects. Each table becomes a candidate external object, and each column becomes a field.
DataSource.Table.get('Sample', 'Name', columns)takes the table name, the name of the column to use as the record name, and the column list.- Every table needs an
ExternalIdcolumn and aDisplayUrlcolumn. These map to the standardExternalIdandDisplayUrlfields on the external object. DataSource.Columnhas typed factory methods such astext,url, andnumber. Text columns take a length.
The schema is read at sync time, not at query time. If your external system adds a column, the external object doesn't gain a field until someone runs Validate and Sync again.
query(): returning rows
query() receives a DataSource.QueryContext that describes the request. It includes the table, the selected columns, the filter, the sort order, and the limit and offset. You return a DataSource.TableResult.
The sample builds its rows by hand. A real adapter would make an HTTP callout, parse the response, and build one Map<String, Object> per row. Each map is keyed by column name. The keys must match the column names you declared in sync().
DataSource.QueryUtils.process(context, rows) is the shortcut. It applies the query's filters, sorting, and limit to your rows in memory, then returns the result. It is a good fit for small data sets. For large ones it means you fetch everything and let Salesforce trim it afterward.
Pushing work to the external system
The in-memory shortcut has a cost. If the external table has 500,000 rows and the user asks for LIMIT 20, process() still needs all 500,000 rows in the heap. The alternative is to translate the query context into the external system's own query parameters.
You read context.tableSelection and build the callout from it. This sketch assumes a hypothetical API that accepts limit and minPrice parameters, and a named credential called Product_API:
override global DataSource.TableResult query(DataSource.QueryContext context) {
Integer maxRows = context.maxResults;
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('callout:Product_API/products?limit=' + maxRows);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new DataSource.OAuthTokenExpiredException(
'Unexpected status ' + res.getStatusCode());
}
List<Object> items = (List<Object>) JSON.deserializeUntyped(res.getBody());
List<Map<String, Object>> rows = new List<Map<String, Object>>();
for (Object item : items) {
Map<String, Object> m = (Map<String, Object>) item;
rows.add(new Map<String, Object>{
'ExternalId' => String.valueOf(m.get('id')),
'DisplayUrl' => 'https://example.com/items/' + m.get('id'),
'Name' => m.get('name')
});
}
return DataSource.TableResult.get(context, rows);
}Two cautions about this sketch:
DataSource.TableResult.get(context, rows)returns your rows as they are. It does no filtering. Use it only when the external system has already applied the filter and sort. If you aren't sure it did, keepprocess().DataSource.OAuthTokenExpiredExceptionis the framework's way to signal an expired token, not a general error. For other failures, throw aDataSource.DataSourceExceptionso the user sees a clear message.
Registering and using the adapter
- Save both classes in your org, or deploy them from source control.
- In Setup, create an external data source. Set the Type to Salesforce Connect: Custom and pick your provider class as the Custom Adapter.
- Choose the identity type and authentication protocol that your provider's
getAuthenticationCapabilities()allows. - Save, then click Validate and Sync. This calls
sync()and lists the tables you returned. - Select the tables to create as external objects, then grant access with permission sets as you would for any other external object.
After that, the external object behaves like any other. SOQL and Apex queries, list views, and lookup relationships all work. Behind each one, Salesforce calls your query() method.
Gotchas
- Callouts from
query()count against Apex callout limits. A page that runs several queries can hit the per-transaction callout cap. - Apex governor limits also apply, including heap size and CPU time. Parsing a large JSON response in
query()is the usual cause of failures. - Each query is a live request. Slow external APIs mean slow pages, and the framework doesn't cache for you.
- Rename a column in
sync()and existing queries, layouts, and list views that reference the old field break after the next sync. - Write capabilities need more work than reads. You must implement
upsertRows()anddeleteRows(), return per-row results, and handle partial failures.
Exercise
A custom adapter's query() returns every row from an external table with 200,000 records using DataSource.QueryUtils.process(context, rows). A user opens a list view that shows 20 rows. Why is this a problem, and what is the fix?
Show answer
process() filters, sorts, and limits in memory, so the connection must first load all 200,000 rows into Apex. That risks heap, CPU, and callout time limits, and it is slow for the user. The fix is to read the filter, sort, and limit from the query context and pass them to the external system's API, so only the needed rows come back. Then return them without in-memory processing, for example with DataSource.TableResult.get(context, rows), only when the external system has applied the filter and sort itself.
Exercise
You add a Color column to the external system and to your sync() method, but the external object has no Color__c field. What step is missing?
Show answer
Run Validate and Sync on the external data source again. sync() is called only at sync time, so the external object's fields change only when an admin syncs and selects the updated table.