Route and transform messages¶ In the previous tutorial, you learned how to develop, deploy, and test your first integration in WSO2 MI. In this tutorial, you will learn how to call an HTTP backend service and dynamically build a payload. What you'll build¶ Let's consider a scenario where a client sends a deposit request to the Bank API deployed in WSO2 Integrator: MI. The API calls a currency converter service to convert the amount to USD, and then responds to the client with the converted deposit value and status. What you'll learn¶ How to create an API resource. How to use the HTTP connector. How to use expressions. How to use the Mediator TryOut. Prerequisites¶ You need Visual Studio Code (VS Code) with the WSO2 Integrator: MI for VS Code extension installed. Info See the Install WSO2 Integrator: MI for VS Code documentation to learn how to install WSO2 Integrator: MI for VS Code. You must have completed the Develop an Integration API tutorial under Build your first Integration before proceeding. Start the Develop an Integration API tutorial if you haven’t completed it yet. Follow the instructions below to modify the API to call an HTTP endpoint and dynamically build a payload. Step 1 - Create a new API resource¶ To develop the above scenario, let's get started with creating a new API resource in the Bank API. Click on the Service Designer () icon of the Bank API in the WSO2 Integrator: MI Project Explorer to open the Service Designer. Note The Service Designer icon will appear when you hover over the API name in the Project Explorer. In the Service Designer, click the + Resource button to add a new API resource. In the Add API Resource pane, set /deposit as the Resource Path and select the POST method. Finally, click Create to add the new API resource. Step 2 - Design the integration¶ Now, it's time to design the bank deposit flow. Follow the steps below to create the integration. Open the Resource View of the newly created API resource by clicking the POST /deposit resource under Available resources in the Service Designer. After opening the Resource View, click on the Start node on the canvas to set an input payload for the integration flow. Note Setting an input payload for the integration flow is not mandatory. However, it is recommended, as it will be used to enable expression suggestions and support the Mediator TryOut features, which you will explore in later steps of this tutorial. Click Add Request, provide the following details, then click Add. Finally, click Save to complete the input payload setup. Name Request body sample1 { "currency":"EUR", "amount":100 } Click on the + icon on the canvas to open the Mediator Palette. To convert the amount from the given currency to USD, you need to call a currency converter service. You can use the following currency converter service as the backend. URL https://dev-tools.wso2.com/gs/helpers/v1.0/currency/rate HTTP Method POST Request payload format { "fromCurrency" : "EUR", "toCurrency" : "USD" } Search for post in the Mediator Palette to add the HTTP POST operation for currency conversion. Click + Add new connection to create a new connection. Select HTTPS and fill in the following details to create a connection to currency converter service. Finally, click Add in the Add New Connection form to create the connection. Property Value Connection Name CurrencyConverter Base URL https://dev-tools.wso2.com/gs/helpers/v1.0 Provide /currency/rate as the Relative Path, and uncheck Overwrite Message Body. In the next step, we’ll create the payload required for the HTTP POST operation. Note The Overwrite Message Body option determines whether the current payload should be replaced with the response from the HTTP call. Since you need to preserve the original payload to extract the amount, make sure to uncheck Overwrite Message Body. When this option is unchecked, the response will be stored in the specified output variable instead of overwriting the original payload. In the Request Body box, enter the following sample JSON object. In the next step, you will use an inline expression to extract the currency from the incoming payload and insert it into this JSON object. What is an expression? Expressions in WSO2 Integrator: MI allow you to dynamically access, evaluate, and manipulate message content during processing. To explore expressions in detail, see the Expressions documentation. { "fromCurrency": " ", "toCurrency": "USD" } In the JSON object, place your cursor in the corresponding location (next to "fromCurrency": "), click on the inline expression editor () icon, then select Payload → currency, and click Add to insert the inline expression into the JSON object. Finally, click Submit to insert the HTTP POST operation into the integration flow. Tip Since you're halfway through the flow, it's a good time to verify everything so far. You can use the Mediator TryOut feature to execute the flow up to a specific mediator and inspect its input and output. To explore this feature in detail, see the Mediator TryOut documentation. Here, we’ll use this feature to check the output of the HTTP call. On the canvas, click the HTTP POST operation to open the Edit pane, then select the Tryout tab. Once the data is loaded, click Run to execute the flow through this mediator and review the output. Expand the Variables section and check the http_post_1 → payload element to view the JSON response from the currency converter service. Info The output variable of the HTTP call contains the following data: Payload – The response body of the HTTP call. Attributes – Metadata such as the status code. Headers – The response headers of the HTTP call. The currency converter service returns a JSON object like {"fromCurrency":"LKR", "toCurrency":"USD", "rate":0.0033}. Since the response is stored in the variable http_post_1, you can access this JSON object using the expression vars.http_post_1.payload. You will work with this data in the upcoming steps. Click the + icon placed just after the HTTP POST operation to open the Mediator Palette to add an If Else Mediator to check the HTTP status code and continue the integration accordingly. Under Mediators, search for if else and select the If Else mediator. You will use an expression to define the condition for the If Else mediator. This condition checks whether the HTTP status code is 200 and determines which flow to execute. If the status code is 200, the integration will convert the request amount and send a deposit success message. Otherwise, it will send an error message to the client. In the Add If Else Mediator pane that appears, click on the expression editor () icon to open the editor. Select Variables → http_post_1 → attributes → statusCode to extract the HTTP status code from the POST response. Next, type a space to display the list of operators. Select the == (equal) operator and enter 200 to complete the condition. Finally, click Add to insert the If Else mediator into the integration flow. Click on the + icon in the Then branch on the canvas to open the Mediator Palette. This branch executes when the HTTP status code is 200. Under Mediators, select the Payload mediator. In the next step, you will use a template with inline expressions to calculate the converted amount based on the incoming payload and the exchange rate returned from the HTTP POST call. Tip You can use the following pre-filled template in the Payload box to skip the inline expression insertion steps and continue from Step 23. { "status": "successful", "amountDeposited": ${payload.amount * vars.http_post_1.payload.rate} } In the Payload box, enter the following sample JSON object. In the next step, we’ll use the inline expression editor to calculate the converted amount and insert it into this JSON structure. { "status": "successful", "amountDeposited": } In the JSON object, place your cursor in the corresponding location (next to "amountDeposited":), click on the inline expression editor () icon, then select Payload → amount. Next, append * vars.http_post_1.payload.rate to the expression, and click Add to insert the inline expression into the JSON object. Finally, click Add to insert the Payload mediator into the integration flow. Click on the + icon in the Else branch on the canvas to open the Mediator Palette. This branch executes when the HTTP status code is not 200. Select Payload mediator under Mediators. In the Payload box, enter the following template to create a new payload for the error message. Then, click Add to insert the Payload mediator into the integration flow. Info In case of an error, the currency converter service returns a JSON object containing an error message and an error code. This template uses the message field from the converter service response to generate the error payload. { "status": "unsuccessful", "error": "${vars.http_post_1.payload.message}" } Click on the + icon placed just after the If Else mediator to open the Mediator Palette to add a Respond Mediator to respond the message to the client. Select Respond mediator under Mediators, and click Add to insert it to the integration flow. You may refer to the following API and HTTP connection for reference, Bank API Info You can view the source view by clicking on the Show Source (</>) icon located in the top right corner of the VS Code. Design ViewSource View <?xml version="1.0" encoding="UTF-8"?> <api context="/bankapi" name="BankAPI" xmlns="http://ws.apache.org/ns/synapse"> <resource methods="GET" uri-template="/"> <inSequence> <payloadFactory media-type="json" template-type="default"> <format>{ "greetings":"Welcome to O2 Bank !!" } </format> </payloadFactory> <respond/> </inSequence> <faultSequence> </faultSequence> </resource> <resource methods="POST" uri-template="/deposit"> <inSequence> <http.post configKey="CurrencyConverter"> <relativePath>/currency/rate</relativePath> <headers>[]</headers> <requestBodyType>JSON</requestBodyType> <requestBodyJson>{ "fromCurrency": " ${payload.currency} ", "toCurrency": "USD" } </requestBodyJson> <forceScAccepted>false</forceScAccepted> <disableChunking>false</disableChunking> <forceHttp10>false</forceHttp10> <noKeepAlive>false</noKeepAlive> <forcePostPutNobody>false</forcePostPutNobody> <responseVariable>http_post_1</responseVariable> <overwriteBody>false</overwriteBody> </http.post> <filter xpath="${vars.http_post_1.attributes.statusCode == 200}"> <then> <payloadFactory media-type="json" template-type="default"> <format>{ "status": "successful", "amountDeposited": ${payload.amount * vars.http_post_1.payload.rate} }</format> </payloadFactory> </then> <else> <payloadFactory media-type="json" template-type="default"> <format>{ "status": "unsuccessful", "error": "${vars.http_post_1.payload.message}" } </format> </payloadFactory> </else> </filter> <respond/> </inSequence> <faultSequence> </faultSequence> </resource> </api> HTTP Connection Info You can view the source view by clicking on the Show Source (</>) icon located in the top right corner of the VS Code. Design ViewSource View <?xml version="1.0" encoding="UTF-8"?> <localEntry key="CurrencyConverter" xmlns="http://ws.apache.org/ns/synapse"> <http.init> <connectionType>HTTPS</connectionType> <baseUrl>https://dev-tools.wso2.com/gs/helpers/v1.0</baseUrl> <authType>None</authType> <timeoutAction>Never</timeoutAction> <retryCount>0</retryCount> <retryDelay>0</retryDelay> <suspendInitialDuration>-1</suspendInitialDuration> <suspendProgressionFactor>1</suspendProgressionFactor> <name>CurrencyConverter</name> </http.init> </localEntry> Step 3 - Run the integration¶ Now that you have updated the integration, it's time to deploy the integration to the WSO2 Integrator: MI server runtime. Click the Build and Run icon located in the top right corner of VS Code. Step 4 - Test the integration service¶ Once the Runtime Services interface is open, select the BankAPI, and click the Try It button. Select the /deposit resource and click Try it Out to test the API. Provide a JSON payload and click the Execute button to invoke the API. You may use the following sample payloads to test the API. Amount in US dollar (USD) { "currency":"USD", "amount":456 } Amount in Japanese yen (JPY) { "currency":"JPY", "amount":897 } Check the response received from the server and verify that the currency conversion has been applied correctly. Congratulations! You have now learned how to create an API resource, use the HTTP connector, work with expressions, and test mediators using Mediator TryOut. What's next?¶ So far, you have learned how to route and transform the payload efficiently. Next, you'll explore how to connect to a SaaS service to send an email. Click on the Next button below to continue to the next tutorial. ← Previous Next →