There are times where we need to consume services that already have been created in Salesforce and those contain information we need to pull , some of that data it's already prepared with the logic needed and can make our integrations faster.
In this case there are two ways to consume a REST service:
- Using HTTP connector and make a regular request call.
- Using the Salesforce connector and use the Invoke apex rest method operation
We'll use the second option for now. Now let's first create a custom REST service in Salesforce, let's create a service called "accountContacts"
The service is really straight forward, it only query accounts and retrieves all contacts that are related. For this you need to set a RestResource (Basically the URI you want to get exposed), declare the the class as global and finally your method should have the right type, in this example we are going to return a List of Accounts. A map collects all the accounts and contacts as a sublist of each account (This is a regular query with a nested query [subquery]).
Once the service is saved and ready in Salesforce we can verify the data is coming as expected using any tool, in this case I just called Force.com workbench and selected the REST Explorer option. Basically our endpoint should be something like:
As we can see in the previous image, we get a list of accounts and on the contacts Object we get the related contacts are already created. At this point we are ready to call this service from any client, we will use Mulesoft.
Now, let's create a new Mule 4 project, and add a new flow with the Invoke apex REST method operation, we need to set out credentials (username, password, token)
For this example I'm setting a Scheduler component which we can trigger manually from the project to check the results. The flow will look like this:
The Salesforce configuration will have this values set:
Request: We will set "payload" (even the payload comes as null)
Apex Class Name: AccountContacts just as we set it in Salesforce
- Apex Class Method Name: In this we need the next sintax:
- We will use this: getAccountContacts^/accountContacts^HttpGet^String
And that's pretty much it!, now in order to get the full list of values we just need to put a DataWeave component and reference your_class_name_output (getAccountContactsOutput) and we should be able to see the output.
In case you need to call a POST / PUT request, as mentioned on this knowledge base you can pass as additional the parameters.
Hope this helps and let you consume those REST services easier.