+
+

Lab 2: Implementing API in Anypoint Studio

Overview

By now you’ve had an opportunity to explore Anypoint Platform, available resources and how it can help with bringing together disparate applications. Now, it’s time that you try implementing an API that will route information to one of several back end systems, based on the type of request that was passed to your API.

Learning Objectives

  • Implementing a Mulesoft Anypoint Studio project from a REST API specification on Exchange

  • Consume existing system APIs to perform validation.

Step 1: Create an API implementation Using Anypoint Studio

Now that you’ve had an opportunity to explore the API specification that is created and shared, you are ready to implement the API using the Anypoint Studio. Complete the following steps to implement the Onboarding Validation Process API.

  1. If Anypoint Studio is not currently open, locate and launch the Anypoint Studio icon in your workshop desktop image.

    1
  2. You may be prompted to choose a directory to store your workspace. Accept the default value and then click on the Launch button to continue.

    2
  3. The Anypoint Studio welcome screen may appear. Click on the Continue to Studio button if it appears.

    3
  4. Whenever you launch Anypoint Studio it will check all of the projects in the current workspace for updates to MuleSoft components. If the Updates Available window appears simply close the window to continue. (Updating components is not required to complete this workshop.)

    4
  5. With Anypoint Studio now open and ready, let’s create a Mule Project to implement the onboarding validation process API.

    lab2 500 studioNewProject1
  6. Name your project with your initials and the name onboarding-validation-papi. Next we will import an REST API specification to scaffold the project with. Click the Green plus sign, and choose "From Exchange"

    lab2 510 studioNewProject2
  7. To access all the assets available in our Anypoint account, we need to log in to the Anypoint org. Click "Add Account"

    lab2 520 studioNewProject3
  8. Enter your credentials provided to you to log in.

    lab2 530 studioAnypoint
  9. Select "No" to provide a password hint for the secure storage. Begin searching for "onboarding-validation". Once you begin typing, studio will search exchange for assets. Select "onboarding-validation-pAPI" published within your root org. Click "Add >" to add the REST API to your project. Then click "Finish"

    lab2 540 studioscaffoldDep
  10. Confirm the API is listed as imported, then select "Finish" to scaffold your project.

    lab2 550 studioscaffoldFinish

    Your Mule project will display as an expanded folder on the left side in the package explorer, within the src/main/mule (Flows) folder, you should see the xml file with your respective project name. When selected, you will see the contents of the file on the canvas in the middle section of the screen. You will notice the canvas has been pre-populated with flows and components. This occurred because you chose to base this implementation on an API Spec that was published in the exchange.

  11. In the canvas, scroll down to the flow named: post:\validate:application\json…

    lab2 600 validateFLow

    You will implement your logic within this flow in the following sections.

Step 2: Re-using API specs as Connectors in a Mule project

In the previous section you walked through scaffolding a new Mule project based on an API specification published in the Anypoint Exchange. Anypoint Exchange will also generate Mule Connectors based on the API Specification. This allows for the re-use of APIs published in the Exchange as connectors in Mule projects. For this project, two specifications will be used.

  1. On the right side of Anypoint Studio you’ll see the Mule Palette. Frequently used message processors are available to drag and drop into your flow(s).

    lab2 610 palette
  2. To add new modules from exchange, click "Search in Exchange". Enter "third" to begin searching, then select "third-party-service-sAPI". click "Add >", then "Finish.

    lab2 620 third party
  3. Review the operations available in this API for you to consume. Feel free to revisit the API in Anypoint Exchange to compare.

    lab2 630 third palette
  4. Repeat the two steps above; searching for "income" to add "income-verification-sAPI" to your project.

    lab2 640 income palette
  5. You can collapse the onboarding-validation-api-main,and the onboarding-validation-api-console flows by clicking the respective blue arrow point down near the flow names

    lab2 650 canvas

Step 3: Connector Configuration

We now have a project ready to call our two system APIs, but we need to provide the location of the endpoints providing these services. To do that, we will create a connector configurations that use properties defined in a Configuration Properties file. This allows your project to have those configurations set at runtime to work with multiple environments (dev, stage, prod)

  1. Create a dedicated Mule config file to hold the connector configurations. This is a best practice particularly for larger projects. In the Package Explorer, right-click on the project root, then select "New" - "Mule Configuration File". Name the file "Global", then click "Finish"

    lab2 700 new config
  2. Now create a yaml file to hold the property values that we will use in our connector configurations. In the Package Explorer, right-click on "src/main/resources" then select "New" - "File". Name the file "config.yaml", then click "Finish"

    lab2 710 new prop
  3. The new file "config.yaml" should be open for entry. Paste the following text into the file and save.

    third-party:
      host: "stg-fins-boi-service-bcvkow.86g03r.usa-e2.cloudhub.io"
      port: "443"
      base-path: "/api"
      protocol: "HTTPS"
      response-timeout: "8000"
    
    income-verification:
      host: "stg-fins-income-verify-xapi-bcvkow.86g03r.usa-e2.cloudhub.io"
      port: "443"
      base-path: "/api"
      protocol: "HTTPS"
      response-timeout: "18000"
  4. Navigate to the "Global" file in your project explorer, or double-click the "Global.xml" file in your Package Explorer to open the Mule Config file. Click "Global Elements" sub-tab, then click "Create"

    lab2 720 global1
  5. Navigate "Global Configurations", then select "Configuration Properties". Click the elipses to select the "config.yaml" file created in a prior step. Click "OK", then "OK" to save the configuration properties.

    lab2 730 global2
  6. Click "Create" again and navigate to "Connector Configuration". Choose "Third-party-service Config", then click "OK"

    lab2 740 thirdconfig
  7. Enter the following values, then click "OK":

    Host

    ${third-party.host}

    Port

    ${third-party.port}

    BasePath

    ${third-party.base-path}

    Protocol

    ${third-party.protocol}

    Response timeout

    ${third-party.response-timeout}

    lab2 750 thridconfig2
  8. Repeat the above two steps for "Income-verification Config" with the following values:

    Host

    ${income-verification.host}

    Port

    ${income-verification.port}

    BasePath

    ${income-verification.base-path}

    Protocol

    ${income-verification.protocol}

    Response timeout

    ${income-verification.response-timeout}

    lab2 760 incomeconfig2

Step 4: Implement Flow Logic

Now connectivity is configured and the logic of our onboarding validation is ready to be implemented. Interacting with the (Mock) government service third-party-service represents requires making numerous consectutive calls. It begins with a establishing a transaction to get a process ID. Then we will upload a file ( a pdf file of a W-2), map the incoming onboarding validation payload to an XML structure for a second call. Then we have to poll the third-party-service as it processes the incomming information to validate it. This may require numerous calls as we await a response indicating completion.

  1. Return to the onboarding-validation-api canvas in the project explorer. Click on the "Transform message" operation created by the scafolding process. DataSense uses the API specification to make it easy to transform data, by showing the expected input and output structures. Here you can drag and drop fields to simplify crafting your logic. This project requires calling some additional services rather than a straight-forward transformation, so delete the "Transform Message" operation.

    lab2 800 step4start
  2. Drag the "Get New Process ID" component from the palette into the validate flow. Select in the "Connector Configuration" drop-down the "Third_party_service_Config" we created in a prior step.

    lab2 810 processID
  3. By default, a connector operation will overwrite the payload, so store the output in a variable for later usage. Under "Advanced", select the "Target Variable" and enter "processId". Click "Apply changes" to save.

    lab2 820 processID2
  4. The next step for our third-party-service is to upload the pdf file of the W-2. But it is not in the payload sent to onboarding-validation. income-verification sAPI has the file we need, and payload has the document ID needed. From the Mule palette, drag "Get files by document id" in "income-verification" to execute after "Get New Process ID" in the canvas.

    lab2 830 document1
  5. Select the "Income_verification_Config" in "Connector Config. click the "fx" (switch to expression mode) on "Document id", and find or enter "payload.incomeVerificationId". This value will come from the onboarding process that calls this API. Similar to above step, the output from this operation should be put into a variable: Under "Advanced" enter "incomeVerificationResponse" into "Target Variable"

    lab2 840 document2
  6. Drag "Upload file attachment for Process ID" from the palette, and provide the following configuration values (be sure to set "expression mode" (fx) for the 2 settings:

    Connector Configuration

    Third_party_service_Config

    Upload file attachment…​(fx)

    vars.incomeVerificationResponse

    Process id (fx)

    vars.processId.body.processId

    File name

    w2file

    Advanced-Target Variable

    uploadResponse

    lab2 850 upload
  7. Drag "Post XML data for Process ID" from the palette. Provide the following configuration values

    Connector Configuration

    Third_party_service_Config

    Process id (fx)

    vars.processId.body.processId

    File name

    xmlFile

    Advanced-Target Variable

    xmlResponse

    lab2 850 upload
  8. To configure "Post xml data for process id request data" click the image::dataweave.png icon. Map the following values, allowing datasense to correctly build the dataweave creating the complex XML structure needed by the third-party-service:

    lastName

    SubmitterEntityIndividualLastName

    firstName

    SubmitterEntityIndividualFirstName

    emailAddress

    SubmitterElectronicAddressText

    activeFromDate

    Activity.FilingDateText

    countryName

    Activity.Party.FormationCountryCodeText

    cityName

    Activity.Party.FormationStateCodeText

    stateProvinceName

    Activity.Party.StateCode

    address.addressLine1

    Activity.Party.Address

    lab2 860 xml
    lab2 862 xml.png
  9. Once the third-party service has the information from the prior steps, it will provide the status with the "Get Status for Process ID" operation. Unfortunately, it takes time to process (The mock service is simulating this by having the first requests for each process ID fail). MuleSoft has an operation to repeat poll a service for this type of situation. From the pallete, under "core", drag "Until Successful" into the end of the flow. Set "Milliseconds Between Retries" to 2000 (2 seconds)

    lab2 870 untilsuccess
  10. Now drag the "third-party-service" "Get Status for Process ID" into the "Until Successful" block. Set the following properties:

    Connector Configuration

    Third_party_service_Config

    Process id (fx)

    vars.processId.body.processId

    lab2 880 status
  11. How do we determine if the status check was successful? a "Choice" router component. Drag "Choice" from the "Core" components in the palette. For the upper path ("when") put the following with expression mode on:

payload.body.submissionStatus == "submission_validation_passed"

+ image::lab2-890-choice.png[width=800]

+ . The upper path for "Choice" router is our happy path. Drag a "Transform Message" from the "Core" in palette. Enter the following dataweave:

%dw 2.0
output application/json
---
{
	thirdPartyProcessId: vars.processId.body.processId,
	thirdPartyStatus: payload.submissionStatus,
	result: "SUCCESS"
}

+ image::lab2-900-success.png[width=800]

+ . When the call to "Get Status…​" is not successful, we will raise an error to allow the "Until Successful" to retry (up to the limit). Drag "Raise error" from "Core" in the palette. Type "ANY" for the "Type" property as we don’t need to track the specific error code at this point.

+ image::lab2-910-raise.png[width=800]

Step 5: Deploy Application to CloudHub

Now that development is complete, it is time to test the API. The Application can be run or debugged locally, but this lab is going to cover deploying the application to CloudHub, MuleSoft’s IPAAS. This can be done a number of ways, including straight from Anypoint Studio.

  1. Right-click on the project in Package Explorer, select "Anypoint Platform", then "Deploy to CloudHub".

    lab2 1000 clouddeploymenu
  2. Confirm an appropriate (and unique for this workshop) application name. Ensure SANDBOX and the workshop Business group is selected. Then scroll down to "Deploy".

    lab2 1010 clouddeploy
    lab2 1020 clouddeploy2
  3. Log back in through the website https://anypoint.mulesoft.com, and navigate to Runtime manager. Ensure you are in the correct Business Group, and Environment, and locate your application instance. Click on the application, make note of the "Public Endpoint", as you will use this in the next Lab.

    lab2 1050 runtime

    == Summary

Congratulations! You have now seen how to use MuleSoft’s Anypoint Platform and Studio to find and implement an API.

Now go to Lab 3: Testing Loan Application process to see how to test out the bank loan process api to onboard a new customer and use your validation logic as part of the loan origination process.

Submit your feedback!
Share your thoughts to help us build the best workshop experience for you!
Take our latest survey!