Consuming RESTful web service in Mulesoft | Tiny-URL Mule


In this walk through, I would build a mule flow which would receive and payload containing website url address and mule flow would to invoke a restapi and render a tinyurl for the posted url in payload. Based on the content-type we will have a routing logic using choice router.


Drag out an HTTP connector and drop it in the canvas. In the HTTP properties view, set the connector configuration to the as shown HTTP_Listener_Configuration and Set the path and allowed methods as /shorturl and POST repesctively.
Drag and configure a json to object transformer with java.util.HashMap in the class property. Drag out another HTTP connector and drop it into the process section of the flow. In the Global Elements view of HTTP Connector, click Create and in the Choose Global Type dialog box, select Connector Configuration > HTTP Request Configuration and click OK. Then in  the Global Element Properties dialog box, set the following values and click OK. In the HTTP Request properties view, set the path, method and add query params as shown
Lets run the project and post a message to mule application. Application is working as expected. 
Lets refactor the application using subflows and variable to make this more generic.
Instead of passing payload directly in the http query params we would use a flow variable as shown, bring a flow variable and set the value and use the flowvar in query param.
Select both JSON To Object and longUrl then right click, Extract To >> Sub flow, provide appropriate name for the subflow.
In order to support requests with xml and text payload, we will bring in a choice router and move the reusable-conversion code into choice router, then bring in another XML to JSON transformer inside choice router and text payload will be configured as default flow.
For XML flow, we will convert xml to json and then call the reusable conversion code using flow reference. For default flow, we will set the flowvar as shown

Choice Router is configured based on Content-Type as shown below, in the Choice properties view, double-click the route. In the Route Properties dialog box, set the expression to true if the Content-Type is equal application/json and click OK. Repeat same for other flows.
Run and test the project,
Test outputs for different payloads shown below
Play around the http parameters [query and uri params]

No comments:

Post a Comment

Note: only a member of this blog may post a comment.