MuleSoft

Salesforce Composite Connector in MuleSoft

Overview-

  • Salesforce is widely recognized as one of the leading Customer Relationship Management (CRM) platforms, empowering businesses to manage customer interactions, data, and processes. However, for organizations to maximize the potential of Salesforce, it often needs to be integrated with other systems, such as ERP platforms, databases, or third-party applications. These integrations ensure seamless data sharing and efficient workflow management across the entire organization.
  • MuleSoft provides the Salesforce Composite Connector, a powerful tool designed to streamline integrations with Salesforce. This connector leverages Salesforce’s Composite API, allowing developers to bundle multiple API calls into a single request. By doing so, it simplifies complex workflows, reduces network overhead, and enhances the efficiency of Salesforce integration processes.

What is Salesforce Composite API?

  • The Salesforce Composite API is a feature of Salesforce that allows developers to bundle multiple REST API calls into a single request. It is designed to:
    • Optimize network usage by reducing the number of round trips between the client and server.
    • Simplify complex operations by executing related actions in a single transaction.
    • Maintain data integrity by supporting operations within the same transaction context.
  • The Composite API supports various functionalities such as:
    • Batch: Batch allows up to 25 separate unrelated actions to be executed in a single call. Each executes independently, and information is not shared between the calls.
    • Composite: This will sequentially execute a series of actions in a single call. The response from one action can be used as input in the subsequent action.
    • SObject Tree: Creates one or more sObject trees with root records of the specified type. An sObject tree is a collection of nested, parent-child records with a single root record.
    • SObject Collections: Similar to batch, the SObject Collection resource can reduce round trip calls on groups of objects (up to 200) but requires a common action (e.g. Create, Update, Retrieve, or Delete a group of records). This call has the option to specify a rollback behavior in the case of partial failure.
    • Composite Graph: Composite graphs provide an enhanced way to perform composite requests, which execute a series of REST API requests in a single call. Regular composite requests have a limit of 25 subrequests. Composite graphs increase this limit to 500. This gives a single API call much greater power.

Key features of Salesforce Composite APIs-

  • Ensures that all operations in a single request succeed or none are committed, maintaining data consistency.
  • Allows output from one operation to be used as input for another within the same request.
  • Provides detailed responses for each sub-request, making it easier to debug and handle errors effectively.
  • Minimizes API call usage and optimizes resource utilization by consolidating requests.

Benefits of Using Salesforce Composite API with MuleSoft-

  • Combine multiple operations into a single request, minimizing API call limits.
  • Salesforce has API usage limits, and fewer calls mean you use fewer API resources. This helps organizations stay within their API limits, avoiding overages and additional costs.
  • Decrease latency and improve response times by reducing the number of HTTP requests.
  • Handle multiple operations in a single transaction, ensuring better control over data consistency.
  • Composite APIs enable quick and efficient synchronization of data, ensuring that your Salesforce instance and connected systems are updated in near real-time. This reduces delays and improves data accuracy.
  • Composite APIs support transaction-based operations. This means that either all operations within a request are executed successfully, or none are applied if an error occurs. This ensures data integrity and consistency.
  • Before diving into specific APIs, it’s essential to understand the common elements that form the foundation of Salesforce API requests:
    • method:
      • GET: Retrieves data (e.g., querying records).
      • POST: Creates new records.
      • PATCH: Updates existing records.
      • DELETE: Deletes records.
    • URL: The endpoint defining the API resource and action.
      • Example: /services/data/v50.0/sobjects/Account
    • Attributes: Metadata describing the object type and additional identifiers.
      • Example: “attributes”: {“type”: “Account”, “referenceId”: “ref1”}.
    • Body: For POST or PATCH requests, this contains the data to be created or updated.
      • Example: { “Name”: “Salesforce.com”, “BillingCity”: “San Francisco” }.
    • referenceId: A unique identifier assigned to each request in a Composite or sObject Tree API. This allows referencing one request’s output in subsequent requests within the same call, enabling seamless chaining of operations.
      • Example: “referenceId”: “Account1”.
    • allOrNone Flag: A boolean parameter used in Composite Request and sObject Collection APIs to control error handling. If set to true, all changes are rolled back if any request in the batch fails, ensuring data consistency.

Operations that we can Perform using the Salesforce Composite Connector-

Execute composite batch-

  • Composite Batch allows you to execute up to 25 subrequests in a single API call. These subrequests, executed serially, are isolated from each other, ensuring that previous successful operations are not rolled back if a subsequent request fails.
  • Sample Request Body:

[

{

“method”: “PATCH”,

“url”: “/services/data/v50.0/sobjects/account/001J200000BYIQiIAP”,

“richInput”: {“Name”: “Company One”, “BillingCity”:”HYD”}

},

{

“method”: “GET”,

“url”: “/services/data/v50.0/sobjects/account/001J200000BYIQiIAP?fields=Name,BillingCity”

}

]

  • Sample Response Body:

{

“hasErrors”: false,

“results”: [

{“statusCode”: 204, “result”: null},

{

“statusCode”: 200,

“result”: {

“Name”: “Company Three”,

“BillingCity”: “HYD”,

“Id”: “001J200000BYIQiIAP”

}

}

]

}

Execute composite Request-

  • Composite Request enables you to bundle multiple API operations into a single call. Unlike Composite Batch, this method allows you to pass the output of one request as the input to another, creating a seamless workflow. It uses referenceId to link dependent requests.
  • The All or None flag ensures that either all operations succeed, or none are executed, rolling back changes on failure.
  • Sample Request Body:

{

“allOrNone”: true,

“compositeRequest”: [

{

“method”: “POST”,

“url”: “/services/data/v50.0/sobjects/Account”,

“referenceId”: “Account1”,

“body”: {“Name”: “Salesforce.com”, “BillingCountry”:”IND”}

},

{

“method”: “POST”,

“url”: “/services/data/v50.0/sobjects/Contact”,

“referenceId”: “Contact1”,

“body”: {“LastName”: “Smith”, “AccountId”: “@{Account1.id}”}

},

{

“method”: “GET”,

“url”: “/services/data/v50.0/query/?q=SELECT Name, BillingCountry FROM Account WHERE Id=’@{Account1.id}'”,

“referenceId”: “QueryAccount1”

}

]

}

  • Sample Response Body:

{

“compositeResponse”: [

{

“body”: {

“id”: “001J200000BYIfUIAX”,

“success”: true,

“errors”: []

},

“httpHeaders”: {

“Location”: “/services/data/v50.0/sobjects/Account/001J200000BYIfUIAX”

},

“httpStatusCode”: 201,

“referenceId”: “Account1”

},

{

“body”: {

“id”: “003J200000ApL7SIAV”,

“success”: true,

“errors”: []

},

“httpHeaders”: {

“Location”: “/services/data/v50.0/sobjects/Contact/003J200000ApL7SIAV”

},

“httpStatusCode”: 201,

“referenceId”: “Contact1”

},

{

“body”: {

“totalSize”: 1,

“done”: true,

“records”: [

{

“attributes”: {

“type”: “Account”,

“url”: “/services/data/v50.0/sobjects/Account/001J200000BYIfUIAX”

},

“Name”: “Account 1”,

“BillingCountry”: “IND”

}

]

},

“httpHeaders”: {},

“httpStatusCode”: 200,

“referenceId”: “QueryAccount1”

}

]

}

Create sObject Tree: –

  • The sObject Tree API allows you to create multiple, related records in a single request. This is particularly useful for handling hierarchical or parent-child data structures, such as creating an account with its associated contacts.
  • Sample Request Body:

[

{

“attributes”: {

“objectType”: “Account”,

“referenceId”: “refer1”

},

“Name”: “Salesforce.com”,

“Phone”: “1234567890”,

“Contacts”: {

“records”: [

{

“attributes”: {

“objectType”: “Contact”,

“referenceId”: “refer2”

},

“LastName”: “Smith”,

“Title”: “President”,

“Email”: “sample@salesforce.com”

},

{

“attributes”: {

“objectType”: “Contact”,

“referenceId”: “refer3”

},

“LastName”: “Evans”,

“Title”: “Vice President”,

“Email”: “sample@salesforce.com”

}

]

}

}

]

  • Sample Response Body:

{

“hasErrors”: false,

“results”: [

{

“referenceId”: “refer1”,

“id”: “001J200000BYIzhIAH”

},

{

“referenceId”: “refer2”,

“id”: “003J200000ApLMHIA3”

},

{

“referenceId”: “refer3”,

“id”: “003J200000ApLMIIA3”

}

]

}

sObject Collection-

  • The sObject Collection API simplifies batch operations for creating, updating, or deleting multiple records in one call.
  • Sample Request Body to get sObject collections:

{

“type”:”Account”,

“ids” : [ “0015h00001YTNC2AAP”, “0015h00001ZHUUJAA5”],

“fields” : [“Name”,”BillingCity”, “BillingState” ]

}

    • Sample Response Body:

[

{

“attributes”: {

“type”: “Account”,

“url”: “/services/data/v61.0/sobjects/Account/0015h00001YTNC2AAP”

},

“Name”: “Sample Account for Entitlements”,

“BillingCity”: null,

“BillingState”: null,

“Id”: “0015h00001YTNC2AAP”

},

{

“attributes”: {

“type”: “Account”,

“url”: “/services/data/v61.0/sobjects/Account/0015h00001ZHUUJAA5”

},

“Name”: “Edge Communications”,

“BillingCity”: “Austin”,

“BillingState”: “TX”,

“Id”: “0015h00001ZHUUJAA5”

}

]

Let’s demonstrate a simple use case to understand about how to use execute composite request using a salesforce composite connector.

Use Case-

Let’s create two Account records and one child Contact record for each Account in a single API call using the Salesforce Composite.

Setting up the Salesforce Composite Configuration-

Create a connected app in Salesforce-

  1. Log in to the salesforce account> Open Setup in the top right corner.

2. Click on App Manager under the Apps sections and click on New Connected App > Create a New Connected app > continue

3. Fill the details like connected app name, Contact Emails and also enable OAuth Settings then Provide Call back URL and also provide scopes for the connected App(here I’m providing full access). After that scroll down and click on Save and then click on continue.

4. Now a new connected App has been created and it’ll directly navigate to the newly created connected app. Click on Manage consumer details.

5. Copy both the Consumer key and the Consumer Secret

Before Implementing the use case make sure you have salesforce-connected app credentials like clientId, clientSecret, call back URL.

Salesforce Composite Configuration in Anypoint Studio:

6. Create a new project in Anypoint Studio. To create click on the “File” menu at the top left corner of the window. From the dropdown menu, select “New” and then choose “Mule Project”.

7.  A dialog box will appear where you can enter details about your new Mule project. Provide a name for your project in the “Project name” field. And click on finish.

8. Import the Salesforce Composite module from the Exchange. Click on Search in Exchange in Mule palette > search for the Salesforce composite connector and add it to the selected modules then click on Finish

9. Now click on the global elements in the project file And click on Create.

10. Search for Salesforce Composite config and click on it. It will open the Salesforce Composite configuration.

Note:

The Salesforce Composite Connector supports the following authentication methods:

  • OAuth v2.0
  • OAuth JWT
  • OAuth SAML
  • OAuth Username and Password
  • Token-based Connection

Here I am using OAuth v2.0.

11. Select connection as OAuth v2.0 and provide all the necessary details like Consumer key, Consumer secret, Callback path, Authorize path, External callback url and Resource owner id as “attributes.queryParams.resourceOwnerId” and click Ok

Implementation:

12. Create a keystore and add that keystore under src/main/resources folder

13. Drag and drop the HTTP Listener Connector into the project from the HTTP module. Configure the listener, and select protocol as HTTPS, set the host to All interface (0.0.0.0), port number as 8082 by clicking on the (+) in Connector configuration.

14. Click on TLS, select TLS Configuration as Edit inline and provide Key Store configuration such as type, Path, and key Password and Password then click on ‘OK’

15. Set the path for the listener component as ‘demo’

16. Drag and drop the logger from the core module and configure the message as #[payload] to log the payload.

17. Drag and drop Execute composite batch from the salesforce composite module then select connector configuration that we created before.

18. Drag and drop the Transform message from the code module, transform the payload to JSON, and add a logger to log the payload.

19. Deploy the application, to deploy the application we have right click on the project, go to Run As-> Mule Application

20. After deploying the application, To authorize with the resource owner ID, Open any browser and enter the URL:

http://localhost:8082/authorize?resourceOwnerId=demo .

You will be redirected to the Salesforce Login page, where you can log in with your credentials and grant access to the application.

21. Open Postman, select method as post, and add URL:

http://localhost:8082/demo?resourceOwnerId=demo and add request body as shown below and then hit the request.

Request Body:

{

“allOrNone” : true,

“compositeRequest”: [

{

“method”: “POST”,

“url”: “/services/data/v50.0/sobjects/Account”,

“referenceId”: “accountRefer1”,

“body”: {

“Name”: “tgh.com”,

“BillingCountry”:”IND”

}

},

{

“method”: “POST”,

“url”: “/services/data/v50.0/sobjects/Contact”,

“referenceId”: “contactRefer1”,

“body”: {

“LastName”: “Smith”,

“FirstName”: “John”,

“AccountId”: “@{Account1.id}”

}

},

{

“method”: “POST”,

“url”: “/services/data/v50.0/sobjects/Account”,

“referenceId”: “accountRefer1”,

“body”: {

“Name”: “mulesoft.com”,

“BillingCountry”:”IND”

}

},

{

“method”: “POST”,

“url”: “/services/data/v50.0/sobjects/Contact”,

“referenceId”: “contactRefer1”,

“body”: {

“LastName”: “Chris”,

“FirstName”: “Evans”,

“AccountId”: “@{Account1.id}”

}

},

]

}

When you send the request, The response will contain a compositeResponse array with details for each sub-request, including success status, resource IDs, HTTP status codes, and locations, mapped to their respective referenceId.

The created records can be verified directly in Salesforce by checking the object records.

Author

Teja Dannina

Leave a comment

Your email address will not be published. Required fields are marked *