Org Skills

Inbound APIs — composite family, Apex REST, Bulk API 2.0, limits

Supporting material for salesforce-integration. Agents load it on demand; it ships inside the skill folder.

RawSource

Target: Spring '26 (API 66.0). Sources: REST API Developer Guide, Composite Graph limits, Bulk API 2.0, Apex REST.

1. Choosing the resource

Resource Size Transactional? Use for
POST/PATCH /sobjects/{Object}/{ExternalIdField}/{value} 1 record yes (single DML) The default inbound write: idempotent upsert
/composite/sobjects ≤ 200 records of one type allOrNone flag Straight collection insert/update/upsert/delete
/composite ≤ 25 subrequests yes with "allOrNone": true; subrequests can reference earlier results (@{ref.id}) A small multi-object business operation in one round trip
/composite/tree ≤ 200 records, one root type, nested children yes Creating a parent with its children in one call
/composite/graph ≤ 500 subrequests per graph, several graphs per request per graph — each graph commits or rolls back on its own; the request as a whole does not Large, deep object graphs; batches of independent units of work
/composite/batch ≤ 25 subrequests no — each subrequest is its own transaction, haltOnError only stops later ones Unrelated reads/writes bundled to save round trips
Bulk API 2.0 ingest millions per batch, server-chunked Nightly loads, migrations, anything over ~100 k records
GraphQL API reads n/a Shaped reads for a UI without writing an Apex controller

Sizing rule: prefer many small graphs over one big graph — 50 graphs of 10 nodes process better than one graph of 500, and a failure blast radius stays small.

2. Bulk API 2.0 — the four calls

POST /services/data/v66.0/jobs/ingest
{ "object": "Order__c", "operation": "upsert",
  "externalIdFieldName": "ERP_Id__c", "contentType": "CSV", "lineEnding": "LF" }

PUT   /services/data/v66.0/jobs/ingest/{jobId}/batches      # body: the CSV, ≤ 150 MB
PATCH /services/data/v66.0/jobs/ingest/{jobId}              # { "state": "UploadComplete" }
GET   /services/data/v66.0/jobs/ingest/{jobId}              # poll until JobComplete / Failed
GET   /services/data/v66.0/jobs/ingest/{jobId}/failedResults # always read this, not just the state

Query jobs follow the same shape on /jobs/query with {"operation": "query", "query": "SELECT …"} and GET /jobs/query/{id}/results?maxRecords=50000, paging with the Sforce-Locator response header.

Rules: sort the file by parent Id to avoid row locks, use serial mode when the data is skewed, and never assume "job complete" means "all rows succeeded".

3. Apex REST — only when the standard API cannot express the contract

@RestResource(urlMapping='/v1/orders/*')
global with sharing class OrderRest {

    global class OrderDto {
        global String erpId;
        global String accountErpId;
        global Decimal total;
    }

    global class ResultDto {
        global String erpId;
        global String salesforceId;
        global String error;
    }

    @HttpPost
    global static void upsertOrders() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        try {
            List<OrderDto> input = (List<OrderDto>) JSON.deserialize(
                req.requestBody.toString(), List<OrderDto>.class);
            if (input.isEmpty() || input.size() > 200) {
                respond(res, 400, new Map<String, String>{ 'error' => 'Send 1–200 orders per call' });
                return;
            }
            List<ResultDto> results = OrderIntakeService.upsertAll(input);   // bulk, USER_MODE inside
            respond(res, 200, results);
        } catch (JSONException e) {
            respond(res, 400, new Map<String, String>{ 'error' => 'Malformed JSON' });
        } catch (Exception e) {
            IntegrationLogger.error('OrderRest', e);                          // survives the rollback
            respond(res, 500, new Map<String, String>{ 'error' => 'Unexpected error', 'ref' => IntegrationLogger.lastRef() });
        }
    }

    private static void respond(RestResponse res, Integer status, Object body) {
        res.statusCode = status;
        res.responseBody = Blob.valueOf(JSON.serialize(body));
    }
}
  • Apex REST classes and their exposed methods are global; the class carries with sharing and the service enforces USER_MODE.
  • Version in the URL, never in a header you control; a new contract is /v2/orders, and /v1 keeps working until its consumers are gone.
  • Accept and return arrays: a per-record endpoint called 5 000 times burns the API allocation and the caller's patience.
  • Return a per-record result with the caller's key (erpId) so partial success is actionable.
  • Tests set RestContext.request/RestContext.response directly — see apex-testing.

4. Limits and headers

Limit Value Where to watch it
API requests / 24 h Edition + licence based Sforce-Limit-Info: api-usage=17543/100000 on every REST response
Concurrent long-running requests (> 20 s) 25 per org REQUEST_LIMIT_EXCEEDED on a slow endpoint under load
SOQL rows per request 2 000 in one REST query page nextRecordsUrl pages the rest
Bulk API 2.0 ingest 150 MB per batch upload Job state and failedResults
Apex REST response 6 MB (sync heap) Paginate the contract, do not raise it
UNABLE_TO_LOCK_ROW — Parallel writes to children of one parent; sort by parent, or go serial

Per-client budgeting: give every consumer its own integration user so api-usage is attributable in Setup → API Usage and in Event Monitoring, and alert at 70 % of the daily allocation rather than at failure.

5. Errors worth designing for

Salesforce error Real cause Contract fix
DUPLICATES_DETECTED Duplicate rules on a bulk insert Upsert on the external Id; narrow duplicate rules for the integration user
ENTITY_IS_LOCKED Record in an approval process Fail loudly, do not retry blindly
STRING_TOO_LONG Source field longer than the Salesforce field Validate and truncate on the sender, never silently on receipt
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY An Apex trigger or flow threw Bypass switch for migrations only; otherwise fix the automation
INVALID_SESSION_ID mid-run Token expired or the integration user was frozen Refresh through the auth library; alert on the user, not the record