Module 4 — Integration
Connect Salesforce with external systems using APIs and event-driven patterns.
What you will learn
- ✓Understand why organizations integrate Salesforce with external systems.
- ✓Choose a suitable integration pattern based on timing, data volume, ownership, and reliability needs.
- ✓Configure secure authentication with Connected Apps, OAuth, Named Credentials, and External Credentials.
- ✓Use REST, SOAP, Bulk, Composite, Metadata, and Tooling APIs appropriately.
- ✓Design outbound messaging, Platform Events, Change Data Capture, and webhook-style solutions.
- ✓Build integration processes with retries, idempotency, monitoring, and actionable error handling.
Study material
1. Why Salesforce integrations are needed
Salesforce is often the system of record for customer and sales information, but it is rarely the only system in an organization. Integrations connect Salesforce to ERP, billing, marketing, identity, data warehouse, customer portals, service platforms, and partner systems. An integration moves data or invokes a business operation so people do not have to copy information manually.
Practical example
When an Opportunity becomes Closed Won, Salesforce sends the order details to an ERP system. The ERP creates the order and returns an order number to Salesforce for the sales team to track.
2. Start with integration requirements
Before choosing an API or tool, document the systems involved, source and target ownership, objects and fields, direction of data flow, expected volume, latency, frequency, security classification, failure behavior, and monitoring owner. The correct design depends on the requirement, not on which API is most familiar.
Practical example
A nightly finance reconciliation can use a batch pattern, while a payment authorization needed during checkout requires a synchronous request-reply interaction.
3. Salesforce integration setup
A typical setup includes a dedicated integration user, the correct permission set, a Connected App or External Credential, an authentication method, endpoint configuration, field mapping, and an integration log strategy. Use separate credentials and endpoints for development, testing, and production. Store configuration in metadata or protected settings rather than hard-coding it in Apex.
Practical example
A company creates a dedicated ERP Integration User with only the required object and field permissions, then gives the middleware a separate production credential that can be revoked without affecting human users.
4. Integration users and least privilege
An integration user represents a system rather than a person. Give it only the permissions needed for the integration and assign a meaningful name and owner. Avoid using an administrator profile for integrations. Review login history, API usage, permission changes, and certificate expiration regularly.
Practical example
A billing integration needs to read Accounts and update Invoice Status, but it does not need to delete Contacts or access internal case notes. Its permission set should reflect exactly that boundary.
5. Connected Apps and OAuth basics
A Connected App defines how an external application connects to Salesforce. OAuth allows an application to obtain an access token without handling a user's password directly. Important concepts include client ID, client secret, authorization server, scopes, access token, refresh token, callback URL, and token lifetime. Choose the OAuth flow based on whether a human user or a server process is authenticating.
Practical example
A middleware service uses a server-to-server authentication approach and receives a token to call Salesforce APIs. A portal where a user logs in may use an interactive authorization flow instead.
6. Named Credentials and External Credentials
Named Credentials provide a safe, reusable reference to an endpoint and its authentication configuration. External Credentials define how Salesforce authenticates to an external system and can map principals to permission sets. This keeps endpoint URLs and secrets out of Apex code and makes environments easier to configure.
Practical example
Apex calls `callout:Billing_Service/invoices` instead of storing a billing URL and token in code. The sandbox and production Named Credentials point to their own billing environments.
Code example
public with sharing class BillingClient {
public static HttpResponse getInvoice(String invoiceId) {
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Billing_Service/invoices/' + invoiceId);
request.setMethod('GET');
request.setHeader('Accept', 'application/json');
return new Http().send(request);
}
}7. Synchronous request-reply pattern
In a synchronous integration, Salesforce sends a request and waits for the external system's response in the same user transaction. It is appropriate when the user needs an immediate result and the operation is quick and reliable. The design must account for timeout, external errors, governor limits, and the possibility that the user retries the request.
Practical example
A service agent clicks Verify Address. Salesforce calls an address service and immediately displays whether the address is valid before the Case is saved.
8. Asynchronous fire-and-forget pattern
An asynchronous integration accepts the Salesforce transaction first and performs external work later. Queueable Apex, Platform Events, Change Data Capture, and middleware queues can support this pattern. It improves user experience and resilience, but the system needs a status model so users can see whether the work is pending, successful, or failed.
Practical example
When a customer updates their address, Salesforce saves the Account immediately and publishes an event. A middleware worker later synchronizes the change with the data warehouse.
9. Request-reply through middleware
Middleware can sit between Salesforce and several downstream systems. Salesforce sends one canonical request to the middleware, which handles routing, transformation, authentication, retries, and response normalization. This avoids placing every downstream detail inside Apex and reduces point-to-point connections.
Practical example
Salesforce sends a Create Customer request to an integration platform. The platform creates the customer in billing, tax, and fulfillment systems, then returns one normalized customer ID.
10. REST API
The REST API is a flexible HTTP API for querying, creating, updating, deleting, and describing Salesforce records. It is commonly used by web applications, middleware, scripts, and lightweight services. Clients send HTTP methods such as GET, POST, PATCH, and DELETE with JSON request and response bodies.
Practical example
A customer portal uses REST API calls to retrieve a user's open Cases and submit a new support request after the user authenticates.
Code example
GET /services/data/vXX.X/sobjects/Account/001XXXXXXXXXXXX
Authorization: Bearer <access-token>
Accept: application/json11. SOAP API
The SOAP API uses strongly typed WSDL contracts and XML messages. It is useful for enterprise systems that already rely on SOAP, formal schemas, generated client code, or strongly defined service contracts. Compared with REST, SOAP messages are more verbose, but the contract can be valuable for strict enterprise integration.
Practical example
A legacy insurance platform generated a SOAP client from Salesforce's enterprise WSDL and uses it to create and update customer policy records.
12. Bulk API 2.0 and batch processing
Bulk API 2.0 is designed for large data volumes and processes jobs asynchronously. A client uploads records, checks job status, and retrieves success or failure results. It is better than making one REST call per record when importing or exporting thousands or millions of rows.
Practical example
Every night, a data platform updates two million Account attributes. It creates a Bulk API job, uploads a CSV file, monitors completion, and stores failed rows for correction.
13. Composite API
Composite API combines multiple REST requests into one HTTP request. It can reduce network round trips and support dependent operations where a later request uses an ID returned by an earlier one. Composite requests should still be designed with transaction size, error handling, and partial success behavior in mind.
Practical example
A mobile application creates an Account, creates a Contact related to that Account, and creates an initial Case in one coordinated request.
Code example
{
"allOrNone": true,
"compositeRequest": [
{
"method": "POST",
"url": "/services/data/vXX.X/sobjects/Account",
"referenceId": "newAccount",
"body": { "Name": "Example Customer" }
},
{
"method": "POST",
"url": "/services/data/vXX.X/sobjects/Contact",
"referenceId": "newContact",
"body": { "LastName": "Patel", "AccountId": "@{newAccount.id}" }
}
]
}14. Metadata API and Tooling API
The Metadata API moves and deploys Salesforce configuration such as objects, fields, permissions, Flows, and Apex metadata. The Tooling API is useful for developer tooling, inspecting metadata, and working with development artifacts. These APIs manage the shape and behavior of an org rather than ordinary business records.
Practical example
A CI pipeline deploys a new custom field, permission set, Flow, Apex class, and LWC from source control into a testing sandbox.
15. Outbound Messages and webhooks
Outbound Messages can send a SOAP notification when configured record changes occur. A webhook is a general pattern where Salesforce or middleware sends an HTTP notification to another system. Notifications should be treated as at-least-once delivery: the receiver must be able to safely process duplicates and retry failures.
Practical example
When a Case is escalated, Salesforce notifies an operations service. The operations service acknowledges the message and creates an incident only if that event has not already been processed.
16. Platform Events
Platform Events provide an event bus for publishing and subscribing to business events. Publishers do not need to know every subscriber, which reduces coupling. Events can be published from Apex, Flow, APIs, or other Salesforce features. Subscribers may include Apex triggers, Salesforce flows, middleware, or external event clients.
Practical example
Salesforce publishes `Order_Submitted__e` after an order is submitted. Billing, fulfillment, and analytics services subscribe independently without changing the order submission code.
Code example
Order_Submitted__e eventMessage = new Order_Submitted__e(
Order_Id__c = order.Id,
Customer_Id__c = order.AccountId,
Submitted_At__c = Datetime.now()
);
Database.SaveResult result = EventBus.publish(eventMessage);
if (!result.isSuccess()) {
// Record the publish error for retry or support review.
}17. Change Data Capture
Change Data Capture publishes changes to supported Salesforce records, including create, update, delete, and undelete information. It is useful when an external data platform needs a near-real-time stream of record changes without a custom event for every field update. Consumers should filter the objects they need and manage replay and retention behavior.
Practical example
A data warehouse subscribes to Account and Contact change events, updates its analytical tables, and uses the change header to understand the operation and changed fields.
18. Streaming and event-driven integration patterns
Event-driven architecture communicates that something happened rather than asking another system to perform a tightly coupled command. It supports multiple consumers and reduces synchronous dependencies. Design event names, payloads, versioning, ordering expectations, replay, retention, and consumer failure handling before publishing events.
Practical example
The event `Customer_Address_Changed` tells subscribers about a business fact. The warehouse updates analytics, the notification service informs the customer, and the fulfillment service updates delivery details independently.
19. Middleware and canonical data models
Middleware provides routing, transformation, orchestration, credential handling, queues, monitoring, and retry capabilities. A canonical data model defines a shared representation of concepts such as Customer, Order, or Product. Canonical models can reduce repeated mappings, but they need versioning and clear ownership.
Practical example
Salesforce calls an Account a Customer Account, while an ERP calls it a Business Partner. Middleware maps both into a canonical Customer model and then maps that model to each downstream system.
20. Kafka and high-volume event architecture
Kafka is a distributed event streaming platform often used when many systems need durable, high-volume event streams. Salesforce can publish events to middleware, which then produces Kafka messages, or a supported connector can bridge the systems. Kafka design requires topics, partitions, keys, consumer groups, retention, ordering boundaries, replay, and dead-letter handling.
Practical example
A retail company publishes customer and order events to an enterprise event platform. Separate consumer groups feed fraud detection, recommendations, analytics, and fulfillment without each system polling Salesforce.
21. Callouts from Apex
Apex callouts send HTTP or SOAP requests to external services. Configure the endpoint using a Named Credential, set timeouts deliberately, validate status codes and response bodies, and avoid making a callout after uncommitted work when the transaction rules do not allow it. Long-running or unreliable work should usually move to Queueable Apex or middleware.
Practical example
A Queueable job sends a newly created warranty claim to an external claims service, records the response status, and marks the claim for retry if the service is temporarily unavailable.
Code example
public class WarrantyCallout implements Queueable, Database.AllowsCallouts {
private Id claimId;
public WarrantyCallout(Id claimId) {
this.claimId = claimId;
}
public void execute(QueueableContext context) {
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Claims_Service/claims');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setBody(JSON.serialize(new Map<String, Object>{
'claimId' => claimId
}));
HttpResponse response = new Http().send(request);
// Persist success or retry status based on response.getStatusCode().
}
}22. Data mapping and transformation
Data mapping defines how source fields correspond to target fields. Transformation may include converting dates, currencies, codes, units, names, or nested structures. Document required fields, defaults, reference lookups, rejected values, and ownership of the mapping. Do not silently discard information that the business needs to reconcile.
Practical example
Salesforce sends `StageName = Closed Won`, while the ERP expects `ORDER_READY`. Middleware applies the documented mapping and records the original Salesforce value for traceability.
23. Reliability: retries, idempotency, and dead letters
Networks fail and messages can be delivered more than once. A retry policy should distinguish temporary failures such as timeouts from permanent failures such as invalid data. Idempotency means processing the same request twice produces one business result. Store an external request ID or event ID and reject or safely ignore duplicates. Unrecoverable messages should move to a dead-letter queue for investigation.
Practical example
If a billing request times out after the ERP created the invoice, retrying without an idempotency key could create a duplicate invoice. The external request ID lets the ERP return the existing invoice instead.
24. Integration security
Protect credentials, tokens, personal data, and business data in transit and at rest. Use TLS, least-privilege users, short-lived tokens where possible, secret rotation, IP restrictions when appropriate, and field-level access controls. Do not write access tokens, passwords, or sensitive payloads to debug logs. Confirm that the integration respects data residency and privacy requirements.
Practical example
A customer identity integration sends only the fields required for verification, encrypts the connection, rotates its certificate before expiry, and masks personal identifiers in monitoring logs.
25. Monitoring, reconciliation, and support
An integration is not complete until it can be operated. Monitor request counts, latency, error rates, event backlog, retry counts, authentication failures, and business outcomes. Keep correlation IDs across systems so support teams can trace one transaction. Reconciliation jobs compare source and target totals and identify missing or mismatched records.
Practical example
A support dashboard shows 98 percent of orders synchronized, 12 failed messages awaiting retry, and the correlation ID for each failure so an engineer can trace it across Salesforce and the ERP.
26. Testing integration solutions
Test authentication, valid payloads, missing required fields, invalid references, timeouts, rate limits, server errors, duplicate delivery, partial failure, retries, and large volumes. Use Apex callout mocks for Apex tests and sandbox or contract-test endpoints for end-to-end verification. Test backward compatibility before changing an event or API payload.
Practical example
Before release, the team proves that a 500 response schedules a retry, a 400 response creates an actionable data error, and repeating the same event does not create a duplicate order.
Code example
@IsTest
private class BillingClientTest {
@IsTest
static void handlesBillingSuccess() {
Test.setMock(HttpCalloutMock.class, new BillingSuccessMock());
Test.startTest();
HttpResponse response = BillingClient.getInvoice('INV-100');
Test.stopTest();
System.assertEquals(200, response.getStatusCode());
}
}27. Choosing the right integration pattern
Use synchronous request-reply when an immediate answer is required and the operation is quick. Use asynchronous processing when the user should not wait or the external system may be slow. Use events when multiple consumers need to react to a business fact. Use batch APIs for large data sets. Use middleware when routing, transformation, orchestration, or enterprise monitoring is substantial. Revisit the choice as volume and reliability requirements change.
Practical example
Address validation is synchronous, customer synchronization is event-driven, nightly finance export is bulk, and a multi-system order process is orchestrated by middleware.
28. Integration delivery checklist
Before production release, confirm ownership, data mapping, authentication, permissions, environments, API limits, timeout and retry rules, idempotency, error routing, monitoring, reconciliation, test evidence, deployment dependencies, rollback, and support documentation. A design document should explain what happens when each system is unavailable.
Practical example
For an order integration, the team documents who owns the Salesforce event, how the ERP acknowledges it, where failed messages go, how duplicates are detected, and how operations can replay a safe message.