Lab 2: Implement the customer creation logic


In the previous lab, we created the project skeleton from the Customer API. Now it’s time to implement it. The Customer API contains all the operations for managing customer data - create (POST), read (GET) , update (PUT) and delete (DELETE). For the purposes of this lab, we will only implement the customer creation represented by the POST method.

Step 1: Customer Implementation

The customer creation logic is as follows:

  1. Create the Account in SDFC to represent the customer

  2. Validate the successful creation of the account

  3. If validation fails,

    1. Raise an error mapped to Bad Request (400 is the status code for Bad Requests)

  4. If successful,

    1. Get Account Details

    2. Convert Response to JSON

The steps that need to be executed are:

  1. With the api view selected, click the Add Module module3_lab2_add_module_symbol sign in the Mule Palette view in order to add the Salesforce Connector and Validation module required for our implementation in the next step.

    module3 lab2 project add modules
  2. Drag and Drop Salesforce Connector and Validation Module and click Finish

    module3 lab2 studio add modules finish

    Notice that we’re leveraging the mule lightweight module-based framework to support our use case. The Salesforce Connector provides connectivity to Salesforce and the Validation Module is a component to implement validations, similar to the concept of an assertion, for validation checks like boolean expressions, null values, specific values, and other conditions. Subsequently, the flow execution can generate out of the box and custom Error Types to the Error handling scopes within your flow.

    At the end the palette should look similar to the following image.

    module3 lab2 palette
  3. Now, you are ready to implement the POST resource operation. Find the post:\customer:application\json:api-config resource flow (at the bottom of the api view)

  4. Delete the generated Transform Message step that returned the sample response from the API specification

    module3 lab2 remove property
  5. From the Mule Palette, select Salesforce​, scroll to Create Single and drag and drop the component to the flow.

    module3 lab2 sfdc drag
    You might be asked to select the version. Always choose the latest one.
  6. Click on Salesforce icon and the configuration will be shown below.

  7. Change its name to Create Account

    module3 lab2 change sfdc create account name

    In order to implement best practices, create a properties file to hold connection credentials for our API implementation. To be ordered, we are going to first create a folder and then create the config file.

  8. Click on src/main/resources in the Package Explorer view, right click and create a New → Folder, name it configuration and click Finish

  9. Click on src/main/resources/configuration in the Package Explorer view, right click and create a New → File, name it config.yaml and click Finish

    module3 lab2 properties create 1
    module3 lab2 properties create 2
  10. Copy the following contents into config.yaml. These are the connection credentials your API will use for the Salesforce connector.

      username: ""
      password: "Elum1379"
      securityToken: "7ZDtkYMazEtbvgdaaPrtMGit"
    module3 lab2 sfdc properties
  11. To finish the configuration of the properties file for your API, click on the api view and click on the Global Elements tab.

    module3 lab2 properties create 3
  12. Click Create, search for properties, select Configuration Properties, click OK, enter config.yaml in the File: attribute and click OK.

    module3 lab2 properties create 4
    module3 lab2 properties create 5
  13. Click the module3_lab2_save_all_button Save All button

  14. Now that you have your properties defined, let’s configure a new connector configuration. Go back to the Message Flow tab where you previously dropped the Salesforce connector and select it.

  15. Click on module3_lab1_plus_button button on the Connector Configuration.

  16. For the connector configuration we are going to put the following properties:

    • username: ${sfdc.username}

    • password: ${sfdc.password}

    • securityToken: ${sfdc.securityToken}

  17. Press Test Connection…​ to check everything is in place.

    module3 lab2 sfdc validate
  18. Press OK (2 times).

    Let’s configure the Salesforce connector to create an Account.

  19. Adjacent to the Type: property click the module3_lab2_sfdc_type_refresh_button refresh button, then select Account.

  20. Remove payload word in the Record box and press Refresh Metadata.

    module3 lab2 sfdc create single

    Now that we have configured the Salesforce connector, we need to create a mapping that will convert the JSON message from the Request to the Account Object that is going to be saved in Salesforce.

  21. Drag and Drop a Transform Component and place it before the Salesforce Connector.

    module3 lab2 add transform
  22. You can use the drag and drop to connect each field from the request (input) to the Salesforce object (output). In this mapping you will also use a function, uuid(), to generate a unique AccountNumber.

    module3 lab2 sfdc create dw complete

    This is the mapping code that the picture reflects. You can copy and paste it into your Dataweave text editor and the UI will reflect the changes

    %dw 2.0
    output application/java
    	BillingStreet: payload.billingAddress.address1,
    	BillingState: payload.billingAddress.state,
    	BillingPostalCode: payload.billingAddress.postalCode,
    	ShippingStreet: payload.shippingAddress.address1,
    	ShippingState: payload.shippingAddress.state,
    	ShippingPostalCode: payload.shippingAddress.postalCode,
    	AccountNumber: uuid(),

    Notice that we first configured the Salesforce connector and then we created the mapping. This was done on purpose. Doing it this way, we can have the metadata that needs to be mapped from the Request to Salesforce.

    Once the Customer is saved, we need to evaluate the response from Salesforce (the request may fail if the information being sent is invalid).

  23. To do this, we are going to add a Validation: is true component. Type is true​ in the Mule Palette

  24. Drag and drop the icon at the end of the Flow.

    module3 lab2 validation in flow
    You might be asked to select the version. Always choose the latest one.
  25. Implement the validation properties

    1. Display Name​: Validate Response

    2. Expression​: #[payload.success == true]

    3. Message​: Account Creation was Unsuccessful

      module3 lab2 validation config

      In the Validation component we are evaluating the Salesforce response.

  26. In the Validation, there are going to be two configuration changes, the Expression and the Message. Also, You will ensure that the out of the box error type is used to generate a validation error.

    1. Validate the response value

    2. If there was an error, we are going to respond with a Bad Request.

  27. Check the error mapping for the validation. Click the Error Mapping tab and click the module3_lab2_validation_error_mapping_plus_button button to view the out of the box error types, note the VALIDATION:INVALID_BOOLEAN is pre-populated so you don’t have to do anything else here.

    module3 lab2 validation error mapping

    In this case we are not going to map the error validation to a custom error. Instead, we are going to add the VALIDATION:INVALID_BOOLEAN to the APIKIT errors.

  28. Now, set the VALIDATION:INVALID_BOOLEAN in the APIKIT:BAD_REQUEST Error handler. Navigate towards the top of the api Message Flow view, locate the error handler, and select the Error Type.

    module3 lab2 validation bad request mapping
    If the Error is not listed write the error name manually.

    Notice that mule provides an easy way to generate and capture out of the box, as well as, custom error types, to enable easy configuration of error handling scenarios.

    You have validated the response, the remaining step consists of retrieving the new account and mapping to the response.

  29. Similar to the earlier step, drag and drop a Query Single component within the Salesforce connector to the end of the flow and configure the following properties:

    1. Display Name​: Get Account Detail

    2. Connector Configurator​: Salesforce_Config (we are reusing the configuration we created before).

    3. Salesforce query​: SELECT Id, AccountNumber, Name FROM Account where Id = ':id'

    4. Parameters​:

      1. Name: "id"

      2. Value:

        module3 lab2 sfdc query single
  30. Now we will create the transform step that will build the service response. To do that drag and drop a Transform Message after the Salesforce icon that was created in the previous step.

  31. Right click on the Transform Message and select Rename. Change the Transform Message text with SFDC Account Detail to JSON.

    module3 lab2 rename transform icon
  32. Click on the icon and let’s see the transformation

    You will see the response from SFDC and the API Response.

    module3 lab2 sfdc response
  33. Map each SFDC field with its corresponding response.

    module3 lab2 sfdc transf mapping

    If you look carefully, you will notice that the Id and AccountNumber are defined as optional in the input. While in the output they are mandatory. That’s why you set a default value.

  34. Click the module3_lab2_save_button Save button.

This concludes the customer creation logic and we are ready to test the API.

Step 2: Error Handling

We built the flow that will create a new user. If there’s an error in Salesforce, you’ll receive a Bad Request. This error message doesn’t give you full visibility into what really happened.

In this section we are going to catch the exception and send the correct error message.

  1. Go to the palette and search for the Try component.

  2. Insert the Try component after the Salesforce connector.

  3. Move the Validation icon inside the Try component.

    module3 lab2 try in flow

    Now we need to configure the error handling. To do that we are going to add an On Error Propagate handler to the Error handling part.

  4. Go to the palette and search for On Error Propagate. Drag and Drop the component inside the Error handling part.

    module3 lab2 on error propagate
  5. Click on the component.

  6. In the Type section click the magnifier glass on the right


    module3 lab2 on error propagate select type
  8. Add a Logger component to log the response.

    module3 lab2 add logger
  9. Configure the component with the value output application/json --- payload

    module3 lab2 add logger conf

    When you press the f(x) button, you will see that a #[] is added to the field. This is because we are going to use a dataweave expression to log the Salesforce response.

    After logging the response, we are going to raise a new error

  10. Search for Raise Error component and insert after the logger.

    module3 lab2 add raise error
  11. Configure the component with the following values:

    • Type: APP:CONFLICT

    • Description: #[payload.errors[0].message]

      In the last step, we are raising a new error type called APP:CONFLICT and we are populating the details, with the Salesforce error message.

      Now we are going to build the Response for this exception.

  12. Go to the APIKit Error handling. Add an On Error Propagate component at the bottom.

    module3 lab2 on error propagate apikit
  13. Click on the Component and configure the Type value with APP:CONFLICT.

    module3 lab2 on error configuration
  14. Add a Transform component inside the On Error Propagate.

    module3 lab2 app conflict transform
  15. Add the following transformation

    %dw 2.0
    output application/json
    {message: error.description}
    module3 lab2 error mapping transformation

    We are mapping the description message we set in the Raised Error component. If you want to see the complete error object, you can add a logger before the transformation.

    We also need to set the http status code. To do that we are going to add a variable inside the transformation component

  16. Click on the module3_lab2_transform_plus_button inside the transformation component.

    module3 lab2 error mapping transformation plus

    A new window will appear

  17. Select Variable in the combo and write httpStatus as Variable Name.

    module3 lab2 httpStatus
  18. Click OK

  19. Remove the script and only add 409

    module3 lab2 httpStatus 409

    That’s it we are ready to go to the next Lab where you will test the API.


In this lab, we

  • Implemented Post Flow

  • Configured Salesforce Connector

  • Save and Retrieve a Salesforce Account Object

  • Handled Salesforce Error

Go Further:

Congratulations! You have completed Lab 2.

Please proceed to Lab 3