Salesforce is the world’s leading customer relationship management (CRM) system. When integrated with Mulesoft, it unlocks numerous capabilities. Together, they can create a flexible ecosystem to automate repetitive workflows, unlock data across the organization, transfer large volumes of data across enterprises, and enable real-time synchronization with organization-wide systems.
MuleSoft provides an out-of-the-box Salesforce connector that supports a wide range of operations, making it easy to build fast, efficient, secure, and robust integrations. As the building blocks are already available, the time to deliver a production-ready integration is substantially reduced.
This article explains the why, what, and how of integrating Salesforce with MuleSoft.
Integrating Salesforce with MuleSoft can enable data flow between Salesforce and other systems like ERPs, databases, legacy systems, cloud services, and third-party applications. It helps eliminate data silos and automate workflows. MuleSoft's out-of-the-box support for Salesforce helps accelerate development time and efforts. MuleSoft can be used to build real-time and batch synchronizations, enhancing organization-wide decision-making with increased visibility.
API-led connectivity is an architectural style that connects data applications using reusable and purposeful APIs. It enables an efficient and secure approach to integrating systems within an organization. Integrating Salesforce with MuleSoft by creating system APIs as building blocks can unlock the ability to build extensive, complex business processes that interact with Salesforce.
The API-led approach can enable organizations to build more processes and integrations with Salesforce using existing reusable components, such as the system and process APIs.
You can use CurieTech’s API Spec Generator tool to further enhance this approach by accelerating the creation of system and process APIs, ensuring consistency, and reducing development time to generate API specifications with simple natural language prompts. CurieTech AI is a specialized AI platform built and optimized for MuleSoft, offering AI agents that help you code, test, and document entire workflows. CurieTech has specialized AI tools to help you create simple, complex integrations with simple prompts.
Let's explore an example of generating a simple API spec to retrieve and create accounts in Salesforce that are secured with client ID enforcement. Once the tool receives and processes the prompt, it generates the complete RAML specification with the specified requirements.
Here is a snapshot of the RAML generated by CurieTech’s API Spec Generator tool.
AI agent integration in the Agentforce ecosystem within Salesforce can leverage MuleSoft to bridge the gap between autonomous AI agents and enterprise systems. Agentforce agents use natural language processing backed by large language models to process and execute complex business tasks. MuleSoft can enable these agents to interact with other systems and access the required information securely across systems.
For example, MuleSoft can integrate HR and IT systems with AI agents to automate employee onboarding with AI instructions. Salesforce has built-in capabilities to import and connect to MuleSoft APIs from Anypoint Exchange, making the process fast and easy.
MuleSoft has out-of-the-box capabilities to listen and react to real-time Salesforce changes. These capabilities allow MuleSoft to build highly scalable, efficient, and robust integrations requiring real-time data syncing. When combined with MuleSoft’s ability to interact with any system, Salesforce CRM capabilities can unlock immense possibilities.
For example, an e-commerce company must notify customers when their orders ship. MuleSoft can listen to events when an order ships to build this integration with Salesforce. Then it can retrieve the shipping and customer information and push a notification to the customer’s email or phone with the tracking information.
In today’s world, new systems are added frequently, catering to specific organizational needs. However, migrating data between systems can be very complex. Tackling relations between various data objects, handling large volumes of data, filtering out unnecessary records, and cleaning up insufficient data can be tremendous obstacles when dealing with data loads. MuleSoft can tackle all these challenges, efficiently handling large volumes of data from one system to another using its batch processing and streaming capabilities.
{{banner-large-graph="/banners"}}
MuleSoft supports various authentication methods to connect to Salesforce, enabling secure and quick integration setup. This section examines three authentication methods: basic, OAuth 2.0, and OAuth JWT.
Basic authentication is the easiest way to connect to Salesforce. It requires an account username, password, and security token. However, this method is considered less secure for production environments, and you should only use it to test connectivity with Salesforce and quickly build proofs of concept.
To start, you only need a security token from Salesforce to set up basic authentication for your account. Follow these steps:
OAuth 2.0 is an industry-standard authorization framework that allows third-party applications to securely access users’ resources without exposing their credentials. It uses access tokens issued by an authorization server to grant limited access to APIs or services. Connecting to Salesforce using OAuth 2.0 consists of three steps:
Here’s how to configure MuleSoft, step by step:
You can use CurieTech’s Code Enhancer tool to create connections or update your existing connections to OAuth 2.0 with simple natural language prompts.
Here's an example of how the Code Enhancer can update all Mule flows with minimal effort. Upload the code package and specify the required enhancements. In this case, the goal is to replace the existing authentication with OAuth 2.0 in all relevant flows.
After submitting the task, Code Enhancer finds the references to existing Salesforce connections in all files and replaces them with the new OAuth 2.0 config.
OAuth 2.0 with JSON Web Token (JWT) uses JWTs as access tokens to transmit claims between parties securely. These digitally signed tokens allow the resource server to verify authenticity and user permissions without calling the authorization server. Connecting to Salesforce using OAuth JWT consists of three steps:
Here are the specific MuleSoft configuration steps:
Real-time data sync is ideal for cases requiring instant updates and consistent information across systems. For example, customer data must remain synchronized between Salesforce and an ERP system to prevent mismatches. Salesforce supports real-time integration through two powerful event-driven features:
To implement real-time sync with Salesforce using MuleSoft, follow these steps:
The following guide walks you through an example of building a real-time sync using MuleSoft. The integration listens for new account record creations in Salesforce, retrieves the necessary fields, and inserts the data into a database.
MuleSoft can be configured to subscribe to the platform event and execute the required business process. This flow subscribes to the platform event triggered on new account creation, retrieves the required fields from Salesforce, and inserts them into a database table: account.
You may have noticed that the flow is missing details like error handling, operation-level connection retries, and a redelivery policy for the channel listener. With AI tools such as CurieTech’s Code Enhancer, you can easily find and fix such omissions through AI.
The following example uses CurieTech’s Code Enhancer tool. The code package is provided, and a step-by-step prompt is added in the description box, describing what needs to be enhanced. Error handling, operation-level retries, and a redelivery policy for the channel listener need to be added to the real-time sync flow.
After submitting the task, CurieTech’s Code Enhancer successfully generated the new files with the enhanced code changes. It added the redelivery policy to the Salesforce channel listener.
It also updated the SF: Query operation to include reconnection configuration with externalized properties.
In addition, it added the error handler to gracefully handle errors, with standard logging messages for each error.
Here is how the flow looks when imported into Anypoint Studio. As instructed, CurieTech’s Code Enhancer updated the flow with all points.
{{banner-large="/banners"}}
Building synchronous processes for large-volume data migrations can stress the systems, causing overload and inefficiency. This is where bulk data processing comes into the picture. It is ideal for migrating large amounts of data between systems or syncing high-volume data regularly.
Salesforce provides bulk data APIs based on REST principles, which are optimized for working with large data sets. Salesforce says any data operation, including more than 2000 records, is a good candidate for bulk operations to execute and manage the workflow asynchronously.
The following example uses a scheduled flow running at a fixed frequency. It then retrieves the data from the file and pushes it to Salesforce by creating a bulk job.
A CSV file is the data source containing three fields: Record ID, Account Name, and Account Phone. This data is read in MuleSoft using the file read operation.
After reading the file, the data is transformed according to Salesforce. The transformation has deferred set to true, enabling data streaming while transforming. This is important when handling massive amounts of data between systems. Streaming helps avoid memory overload by efficiently streaming data into memory from disk.
%dw 2.0
output application/csv lineSeparator = "\n", deferred = true, quoteValues = true
---
(payload default []) map((item, index) -> {
Name: item.Name,
Phone: item.Phone
})
MuleSoft supports Salesforce bulk API operations. To create a bulk job, use the Create Bulk Job API V2 operation. This operation accepts data in CSV format and can be configured to insert/update/delete records for any of Salesforce's objects.
This example configures the operation to insert account records in Salesforce. The external ID field name must be configured when performing operations that require an external ID to identify existing records in Salesforce, like updating or deleting.
<salesforce:create-job-bulk-api-v2
objectType="Account"
operation="insert"
doc:name="SF: Create Account Bulk Job"
doc:id="d30a21af-2328-4112-a20a-77c7510a9043"
config-ref="salesforce-config-jwt"
externalIdFieldName="Id">
<reconnect />
</salesforce:create-job-bulk-api-v2>
A job ID is returned once the batch job is created in Salesforce. This is the unique identifier for the job, which can be used to track its status and perform operations on it.
Here is the complete flow for creating a bulk job in Salesforce.
Bulk job creation flow in Salesforce.
MuleSoft can catch, categorize, and handle error types such as authentication failures, validation issues, or network timeouts. Effective error handling can minimize downtime and ensure smooth processing between flows. This topic covers handling both fatal and non-fatal Salesforce errors.
Here are some of the errors Salesforce can generate, failing the current transaction in progress:
Use a try-catch strategy to handle operation-specific mistakes, and a standard error handler to capture the mistakes not specific to the operation. Here is an example for catching the SALESFORCE: INVALID_INPUT error.
Here is the DataWeave script to extract error details. This DataWeave script can catch any errors from Salesforce and be expanded to include more information.
%dw 2.0
output application/json
---
{
namespace: error.errorType.namespace,
errorType: error.errorType.identifier,
description: error.description,
failingComponent: error.failingComponent
}
Here’s the DataWeave error response.
{
"namespace": "SALESFORCE",
"errorType": "INVALID_INPUT",
"description": "Invalid ID field = 1",
"failingComponent": "sf-extract-data-flow/processors/1 @ sf-sync-app:extract-and-upsert.xml:17 (SF: Retrieve Account Data)"
}
When operating Salesforce with multiple records in a single transaction, some records might be successful while others might fail. In such scenarios, Salesforce doesn’t fail the whole transaction; instead, it returns which records succeeded and failed in the response. Salesforce contains an error object in the response for each record for failed records, containing the error code and error message.
Here is a DataWeave example that extracts the errors from the Salesforce response for account records failing due to the Name field not being present in the request payload. This DataWeave script will work to extract any soft errors from the Salesforce response and can be expanded as needed.
%dw 2.0
output application/json
---
payload.items map {
id: $.id, // Salesforce ID of the record
success: $.successful, // Was the operation successful for this record?
errors: $.payload.errors map {
code: $.statusCode, // Error status code
message: $.message // Error description
}
}
Here is the DataWeave error response.
[
{
"id": null,
"success": false,
"errors": [
{
"code": "REQUIRED_FIELD_MISSING",
"message": "Required fields are missing: [Name]"
}
]
},
{
"id": null,
"success": false,
"errors": [
{
"code": "REQUIRED_FIELD_MISSING",
"message": "Required fields are missing: [Name]"
}
]
}
]
Technical challenges often arise when integrating with Salesforce. Authentication can be challenging due to configuration and permission issues. Managing relationships between objects, especially lookup and master detail relationships, requires understanding Salesforce’s data model and proper sequencing of data operations to maintain referential integrity.
Authentication challenges can arise due to incorrectly configured connected apps or invalid credentials. These issues can lead to token refresh failures or unauthorized access errors while connecting to Salesforce.
Ensuring proper end-system configuration, including error handlers, is essential for maintaining reliable connectivity and avoiding authentication issues. Here are some common specific authentication challenges while setting up OAuth configurations:
There are scenarios when objects in Salesforce have relationships with each other. For example, assume there is an existing integration where Salesforce syncs records with a database with its unique ID per record. The ID syncs back to Salesforce (DB_Account_ID__c) to identify records in Salesforce using the database account ID uniquely. Now, there is a new requirement to sync contact records to Salesforce from the database, which is linked to an account with a unique account ID as the foreign key.
While pulling the record from the database, you have the database account ID, which can link the correct account record to the contact using it as an external ID. Here is how it can be done using DataWeave:
%dw 2.0
output application/json
---
{
// Relationship name in contact object
Account: {
// External ID field used to identify the account record
DB_Account_ID__c: payload.accountId
}
}
When integrating Salesforce with MuleSoft, sticking to best practices makes your integrations easier to maintain, more scalable, and less likely to break. Picking the correct pattern from the start and optimizing the flows helps avoid headaches later. Good error handling means you’re not left guessing when something goes wrong, and documenting what you build saves a ton of time, especially when someone new joins the team or something needs to be fixed.
To support adherence to best practices in MuleSoft code, you can use CurieTech’s Single Repo Code Lens agent to analyze MuleSoft automatically flows for quality, security, and maintainability. Using a simple prompt, the agent provides detailed findings, reasoning, and code recommendations to improve the code.
In the example below, the tool flags hardcoded credentials, inadequate error handling, excessive logging, and a lack of test coverage for the provided flow. These insights can help proactively identify and remediate issues early in the development lifecycle.
The following sections highlight specific best practices for MuleSoft development.
While building integrations with Salesforce, it's essential to identify and choose the correct integration pattern. Building deep into the wrong integration pattern can cause significant issues with scaling and efficiency, leading to high costs in terms of development effort and time.
You can choose from multiple integration patterns, depending on the requirements. Here are some examples:
While building integrations, continuously optimize your integrations for performance and scalability to avoid bottlenecks. Unoptimized integrations tend to fail fast when scaled for higher transaction volumes. Utilizing capabilities like streaming for large payloads, caching, reusable flows, and connection pooling to reuse connections can largely optimize integrations. Also, use the Mule execution engine to your advantage by combining expensive operations and optimizing DataWeave operations.
Implementing effective error-handling strategies is essential to building sustainable and resilient integrations in MuleSoft. Here are some best practices for error handling:
CurieTech’s AI tools can enhance already built flows with a robust error-handling framework that captures errors, transforms them to a standard format, and pushes the notification to an external service like Slack for error reporting. To demonstrate, let's build an error handler using CurieTech’s Integration Generator tool, with a step-by-step prompt on how the error handler functions.
Integration Generator generates the standard error handler flow that captures connectivity errors for HTTP, Salesforce, and the database, along with transformation errors. It converts these to a standard format and pushes them to a Slack channel for error reporting.
Here is how the flows look after being imported into the Anypoint Studio.
The standard error handler flow captures all the specified errors using dedicated error strategies, logs the details, invokes the process, and notifies the error sub-flow.
The process and notify flow creates a standard error format with all the required details, builds a payload for a Slack notification request, and pushes the notification to Slack by calling Slack’s chat.postMessage API.
Here’s the DataWeave script for the standard error structure generated by the AI tool:
%dw 2.0
output application/json
var errorTypeToHttpCode = {
"HTTP:CONNECTIVITY": 503,
"HTTP:BAD_REQUEST": 400,
"HTTP:NOT_FOUND": 404,
"HTTP:METHOD_NOT_ALLOWED": 405,
"HTTP:UNAUTHORIZED": 401,
"HTTP:FORBIDDEN": 403,
"SALESFORCE:CONNECTIVITY": 503,
"SALESFORCE:INVALID_INPUT": 400,
"DB:CONNECTIVITY": 503,
"DB:BAD_SQL_SYNTAX": 400,
"MULE:EXPRESSION": 500,
"MULE:TRANSFORMATION": 500
}
var errorSource = vars.errorSource default "Unknown"
---
{
errorType: error.errorType.asString,
errorDescription: error.description,
failingComponent: error.failingComponent,
errorSource: errorSource,
httpStatusCode: errorTypeToHttpCode[error.errorType.asString] default 500,
timestamp: now()
}
Document all the integration processes with high-level and low-level designs, clearly explaining the integration.
Also, document any processes specific to the integration, like refreshing tokens for certain systems, turning features on or off on demand, etc. This will help onboarding new team members quickly and make sharing knowledge easier during handover sessions.
Nowadays, with AI agents such as CurieTech’s Document Generator, it has become extremely easy to automatically generate documentation for the provided flows. This example uses the real-time sync flow to create a Sequence diagram and a Flow diagram, along with complete documentation for the flow utilizing the document generator agent.
Below is the sequence diagram that CurieTech’s Document Generator generated based on the provided flow. This diagram explains the end-to-end workings of the real-time sync, picking up even the granular details from the flow.
Here is another task snapshot with the detailed steps from the Document Generator response.
{{banner-large-table="/banners"}}
In this article, we discussed integrating Salesforce with Mulesoft in detail, covering everything from connecting to Salesforce to handling different integration scenarios. Utilizing MuleSoft’s capabilities to build real-time integrations and bulk data processes lets organizations create efficient, scalable, and secure integrations to support their data needs. Leveraging MuleSoft empowers organizations to unlock Salesforce's full potential as a CRM, enabling data-driven decisions across teams and sustainable growth.