⚡
SF DEV TOOLKIT
Apex · SOQL · LWC · Patterns
API v62.0
Enterprise Integration
Integration Patterns
Patterns for connecting Salesforce with MuleSoft, REST/SOAP APIs, ETL tools, and event-driven third-party systems.
MuleSoft
REST / SOAP
Platform Events
ETL / 3rd Party
MULESOFT
Anypoint Platform
Connected App
OAuth 2.0
SALESFORCE
REST / Bulk API
Outbound Msg
/ Platform Event
ERP / EXT SYS
SAP · NetSuite · etc
Salesforce Connector — Mule 4 Config XML / Mule DSL
<salesforce:config name="Salesforce_Config">
  <salesforce:oauth-jwt-connection
    consumerKey="${sf.consumerKey}"        <!-- Connected App Client ID -->
    keyStorePath="${sf.keystore.path}"    <!-- JWT signing cert -->
    storePassword="${sf.keystore.pass}"
    principal="${sf.username}"
    tokenEndpoint="https://login.salesforce.com/services/oauth2/token" />
</salesforce:config>

<!-- Upsert records using External ID (no SOQL needed in Mule) -->
<salesforce:upsert
  config-ref="Salesforce_Config"
  type="Account"
  externalIdFieldName="Integration_Id__c">
  <salesforce:records>#[payload]</salesforce:records>
</salesforce:upsert>

<!-- Subscribe to Platform Events from Salesforce -->
<salesforce:subscribe-topic-listener
  config-ref="Salesforce_Config"
  topic="/event/Order_Created__e">
  <flow name="handleOrderCreated">
    <!-- Transform + route to ERP -->
    <ee:transform doc:name="Map to ERP format">
      <ee:message><ee:set-payload>
        %dw 2.0
        output application/json
        ---
        { orderId: payload.Order_Id__c, amount: payload.Amount__c }
      </ee:set-payload></ee:message>
    </ee:transform>
    <http:request method="POST" url="${erp.endpoint}/orders" />
  </flow>
</salesforce:subscribe-topic-listener>
MuleSoft Integration — Best Practices Architecture
// ── 1. Always use External IDs for upsert — avoids SOQL in Mule ──
// Mark Integration_Id__c as externalId=true in field metadata

// ── 2. Use Bulk API 2.0 for large data volumes ──
// Mule's salesforce:bulk-operation auto-batches into 10k-row chunks:
//   salesforce:bulk-insert-v2 / salesforce:bulk-upsert-v2

// ── 3. Handle partial success from Bulk API ──
// Bulk API returns per-record success/failure
// Always process salesforce:failed-records for retry logic

// ── 4. JWT Bearer Token flow (no user interaction, server-to-server) ──
// Steps:
// a) Create Connected App with "Use digital signatures"
// b) Upload server certificate to Connected App
// c) Grant "Admin approved users are pre-authorized" OAuth policy
// d) Pre-authorize your integration user in Connected App settings

// ── 5. Idempotency — always design for replay ──
// Mule may replay events on failure. Your Apex endpoint must be
// idempotent: upsert by External ID, not insert-then-update.
3RD PARTY
Any System
REST API
JSON/XML
SALESFORCE
REST API v62.0
Inbound: Custom REST Endpoint (@RestResource) Apex
@RestResource(urlMapping='/v1/accounts/*')
global with sharing class AccountRestService {

    @HttpGet
    global static AccountResponse getAccount() {
        RestRequest req = RestContext.request;
        String extId = req.requestURI.substringAfterLast('/');

        try {
            Account acc = [
                SELECT Id, Name, AnnualRevenue, BillingCity
                FROM Account
                WHERE Integration_Id__c = :extId
                LIMIT 1
            ];
            RestContext.response.statusCode = 200;
            return new AccountResponse(true, acc, null);
        } catch (QueryException e) {
            RestContext.response.statusCode = 404;
            return new AccountResponse(false, null, 'Not found: ' + extId);
        }
    }

    @HttpPost
    global static AccountResponse upsertAccount() {
        RestRequest req = RestContext.request;
        // Deserialize strongly typed — never parse JSON manually
        AccountPayload payload = (AccountPayload)
            JSON.deserialize(req.requestBody.toString(), AccountPayload.class);

        Account acc = new Account(
            Name = payload.name,
            Integration_Id__c = payload.externalId,
            AnnualRevenue = payload.revenue
        );

        Database.UpsertResult result =
            Database.upsert(acc, Account.Integration_Id__c, false);

        RestContext.response.statusCode = result.isCreated() ? 201 : 200;
        return new AccountResponse(result.isSuccess(), acc, null);
    }

    global class AccountPayload {
        public String name, externalId;
        public Decimal revenue;
    }
    global class AccountResponse {
        public Boolean success;
        public Account record;
        public String error;
        public AccountResponse(Boolean s, Account r, String e) {
            this.success=s; this.record=r; this.error=e;
        }
    }
}
Outbound: Apex HTTP Callout with Named Credential Apex
public class ErpIntegrationService {

    // Named Credential handles auth — no secrets in code
    private static final String ENDPOINT =
        'callout:ERP_API/api/v2/orders';

    @future(callout=true)  // Required if called from trigger
    public static void syncOrderAsync(String orderId) {
        Order__c ord = [
            SELECT Id, Name, Total__c, Status__c
            FROM Order__c WHERE Id = :orderId
        ];

        HttpRequest req = new HttpRequest();
        req.setEndpoint(ENDPOINT);
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('X-Idempotency-Key', ord.Id);  // Prevent duplicates
        req.setTimeout(30000);  // 30s — always set explicit timeout

        Map<String, Object> body = new Map<String, Object>{
            'sfId'    => ord.Id,
            'name'    => ord.Name,
            'total'   => ord.Total__c,
            'status'  => ord.Status__c
        };
        req.setBody(JSON.serialize(body));

        HttpResponse res = new Http().send(req);

        if (res.getStatusCode() == 200 || res.getStatusCode() == 201) {
            Map<String, Object> resp =
                (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
            ord.ERP_Order_Id__c = (String) resp.get('erpId');
            update ord;
        } else {
            // Log to custom Error_Log__c object for monitoring
            ErrorLogger.log('ERP Sync', res.getStatus(), res.getBody(), orderId);
        }
    }
}
SALESFORCE
Publisher
Platform Event
Order_Created__e
EVENT BUS
Pub/Sub API (gRPC)
Subscribe
Any language
CONSUMERS
MuleSoft · Node · Python
Publish Platform Event from Apex Apex
// Platform Events: decoupled, reliable, cross-system messaging
// EventBus.publish() does NOT consume DML statement limits
// Events are committed only if transaction succeeds

public class OrderEventService {

    public static void publishOrderCreated(List<Order__c> orders) {
        List<Order_Created__e> events = new List<Order_Created__e>();
        for (Order__c ord : orders) {
            events.add(new Order_Created__e(
                Order_Id__c     = ord.Id,
                Account_Id__c   = ord.AccountId,
                Total_Amount__c = ord.Total__c,
                Currency__c     = ord.CurrencyIsoCode,
                Created_By__c   = UserInfo.getUserId()
            ));
        }

        List<Database.SaveResult> results =
            EventBus.publish(events);

        for (Integer i = 0; i < results.size(); i++) {
            if (!results[i].isSuccess()) {
                System.debug('Event publish failed: ' +
                    results[i].getErrors()[0].getMessage());
            }
        }
    }

    // Subscribe in Apex trigger on the Platform Event object
    // trigger OrderCreatedTrigger on Order_Created__e (after insert) {
    //     for (Order_Created__e evt : Trigger.new) {
    //         ErpIntegrationService.syncOrderAsync(evt.Order_Id__c);
    //     }                                                            }
}
Subscribe via Pub/Sub API (Python gRPC client) Python
# Salesforce Pub/Sub API — real-time event stream via gRPC
# pip install salesforce-pubsub-client grpcio

import grpc
from pubsub_api_pb2_grpc import PubSubStub
from pubsub_api_pb2 import FetchRequest

def subscribe_to_orders(access_token: str, instance_url: str):
    channel = grpc.secure_channel(
        'api.pubsub.salesforce.com:7443',
        grpc.ssl_channel_credentials()
    )
    stub = PubSubStub(channel)

    def fetch_req_stream():
        yield FetchRequest(
            topic_name='/event/Order_Created__e',
            replay_preset=2,         # LATEST = 2, EARLIEST = 0
            num_requested=100
        )

    metadata = [
        ('accesstoken', access_token),
        ('instanceurl', instance_url),
        ('tenantid', 'your-org-id')
    ]

    for event in stub.Subscribe(fetch_req_stream(), metadata=metadata):
        # Decode Avro-encoded payload
        decoded = avro.decode(event.events[0].event.payload)
        print(f"Order received: {decoded['Order_Id__c']}")
        # Route to ERP, warehouse, etc.
        route_to_erp(decoded)
DATA SOURCE
DB · S3 · SaaS API
Extract
Transform
MIDDLEWARE
Informatica · Boomi · Fivetran
Bulk API 2.0
Upsert by Ext ID
SALESFORCE
Load Target
Bulk API 2.0 — Direct HTTP (Python) Python
import requests, time

class BulkAPIClient:
    def __init__(self, instance_url: str, access_token: str):
        self.base = f"{instance_url}/services/data/v62.0/jobs/ingest"
        self.headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json'
        }

    def upsert_records(self, obj: str, ext_id_field: str, csv_data: str):
        # 1. Create Bulk Job
        job = requests.post(self.base, json={
            'object': obj,
            'operation': 'upsert',
            'externalIdFieldName': ext_id_field,
            'lineEnding': 'LF',
            'contentType': 'CSV'
        }, headers=self.headers).json()
        job_id = job['id']

        # 2. Upload CSV data
        requests.put(
            f"{self.base}/{job_id}/batches",
            data=csv_data,
            headers={**self.headers, 'Content-Type': 'text/csv'}
        )

        # 3. Close job to start processing
        requests.patch(f"{self.base}/{job_id}",
            json={'state': 'UploadComplete'}, headers=self.headers)

        # 4. Poll until complete
        while True:
            status = requests.get(
                f"{self.base}/{job_id}", headers=self.headers).json()
            if status['state'] in ['JobComplete', 'Failed', 'Aborted']:
                break
            time.sleep(5)

        # 5. Get failed records for retry
        failed = requests.get(
            f"{self.base}/{job_id}/failedResults",
            headers={**self.headers, 'Accept': 'text/csv'})
        return {'status': status, 'failed_csv': failed.text}
3rd-Party Integration Checklist Architecture
// ── Authentication ──────────────────────────────────────────────
// ✅ Use Connected App + OAuth 2.0 JWT Bearer for server-to-server
// ✅ Store tokens in Named Credentials — never in Custom Settings
// ✅ Rotate certificates annually; use short-lived access tokens
// ✅ Grant minimum required OAuth scopes (api, refresh_token, etc.)

// ── Data Sync Strategy ──────────────────────────────────────────
// ✅ Always upsert by External ID — never query-then-insert
// ✅ External ID fields: set externalId=true + unique=true in metadata
// ✅ Use Bulk API 2.0 for > 2,000 records (not REST /sobjects/...)
// ✅ Implement retry with exponential backoff for transient failures

// ── Error Handling & Observability ──────────────────────────────
// ✅ Log all API requests/responses to Integration_Log__c object
// ✅ Use Platform Events to signal failures to monitoring systems
// ✅ Never lose data: failed records → retry queue → dead letter queue
// ✅ Alert on error rate > threshold via flow or Apex Batch

// ── Common 3rd-Party Patterns ───────────────────────────────────
// Informatica Cloud: Use Salesforce V2 connector; enable bulk mode
// Boomi AtomSphere:  Use Dynamic Document Properties for Ext IDs
// Fivetran / Census: Read-only Connected App; SF as sync destination
// Heroku Connect:    Bidirectional DB sync; set "Write to Salesforce"
// MuleSoft Anypoint: Use DataWeave for transform; streaming for events

// ── Rate Limits to Know ─────────────────────────────────────────
// REST API: 1,000 req/user/hour (Enterprise), burst to ~5x
// Bulk API 2.0: 150MB/job, 15,000 batches/day
// Streaming/Events: 200,000 event deliveries/24hr (Enterprise)