MuleSoft Technical Guides

Guides for MuleSoft Developers.

Consuming SOAP web service using MuleSoft

Consuming SOAP web service using MuleSoft

This tutorial introduces you to Web Service and creating a high-security consumption of Web Service using SOAP in MuleSoft Anypoint Studio.

What are Web Services?

  • Services available over the web are called Web Services.
  • Web Services enable communication over the web.
  • Provides a standard format/protocol for communication.
  • It is a platform-independent communication.
  • Using Web Services, two different applications, the first implementation in Java and other implementation on C++, can talk to each other.

For better clarity, we can take the example of ordering food in a restaurant. The waiter acts as a medium between customer and kitchen by conveying the order to chef and getting food delivered over the table. In the same way, a web URL acts as a medium of communication whenever we search or do anything over the Web to get the desired results.

Live Example: 

SOAP Example

Lets Look at Kayak, an online travel agency and a fine example of web services. When we search for flights on the panel for the flights on desired date and time then our request is redirected to various APIs. All these airlines take the response and check out for flights, their availability and a response is sent back to Kayak from all these airlines. Further, displaying  results we get from these APIs in a readable format.

Moving on to SOAP:

SOAP plays a central role in the Service Oriented Architecture (SOA) approach for software design and development

  • SOAP stands for Simple Object Access Protocol.
  • SOAP is an application communication protocol.
  • SOAP is a format for sending and receiving messages.
  • SOAP is platform-independent.
  • SOAP is based on XML.
  • SOAP is a W3C recommendation.

 

SOAP Message Structure: 

SOAP Structure

WSDL Format: 

 

Advantages of SOAP:

  • WS Security: SOAP defines its own security known as WS Security.
  • Language and Platform independent: SOAP web services can be written in any programming language and executed in any platform.

Disadvantages of SOAP: 

  • Slow: SOAP uses XML format that must be parsed to be read. It defines many standards that must be followed while developing the SOAP applications. So it is slow and consumes more bandwidth and resources.
  • WSDL dependent: SOAP uses WSDL and doesn’t have any other mechanism to discover the service.

 

Consuming SOAP through MuleSoft 

We are going to consume a SOAP web service and implement different operations with the web service.

[Make sure you have MuleSoft Anypoint Studio 7+ installed on your system.]

Step 1: Make a new project in your Any point Studio by clicking on File>New>Mule Project.

New Project MuleSOft

Step 2: Give a Title to the new project. We have named it consuming_soap in this example.

Giving name to new project

 Step 3: Add file module by clicking on add module in the mule pallet as Add Modules>Web Service Consumer.

Adding FIle Module

Step 4: Make the desired flow with the required components shown in the flow below.

Creating Flow

Step 5: Set various connectors configuration as below.

You can directly use the XML code from below to set the desired configurations.

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:apikit-soap="http://www.mulesoft.org/schema/mule/apikit-soap" xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
	xmlns:http="http://www.mulesoft.org/schema/mule/http"
	xmlns:wsc="http://www.mulesoft.org/schema/mule/wsc" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.mulesoft.org/schema/mule/wsc http://www.mulesoft.org/schema/mule/wsc/current/mule-wsc.xsd">
	<http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="a46b95a3-bc12-4bee-b815-9ee901290d44" >
		<http:listener-connection host="0.0.0.0" port="8081" />
	</http:listener-config>
	<wsc:config name="Web_Service_Consumer_Config" doc:name="Web Service Consumer Config" doc:id="d2f27227-d308-4984-b881-5dbe05a0a8a8" >
		<wsc:connection wsdlLocation="http://www.dneonline.com/calculator.asmx?wsdl" service="Calculator" port="CalculatorSoap12" address="http://www.dneonline.com/calculator.asmx">
			<wsc:web-service-security actor="http://schemas.xmlsoap.org/soap/actor/next" />
		</wsc:connection>
	</wsc:config>
	<flow name="soap_serviceFlow" doc:id="81c9f277-86fa-4fd6-b9cf-4f800f4eda87" >
		<http:listener doc:name="Listener" doc:id="72cb72a0-65ad-4171-92a6-ad1ae121d004" config-ref="HTTP_Listener_config" path="soap"/>
		<set-variable value="#[attributes.queryParams.Number1]" doc:name="Number1" doc:id="7ed7e420-f957-43ed-ac93-302b5bc44355" variableName="var1" />
		<set-variable value="#[attributes.queryParams.Number2]" doc:name="Number2" doc:id="0ac5c0d0-0082-4268-8a51-b2b94f25fdcb" variableName="var2" />
		<set-variable value="#[attributes.queryParams.operation]" doc:name="Operation" doc:id="75701e35-3ec6-4c64-b648-b21708cf07c3" variableName="operation"/>
		<ee:transform doc:name="Transform Message" doc:id="efafe623-01c4-4e3c-93b6-7c9680d29b2b">
					<ee:message>
						<ee:set-payload><![CDATA[%dw 2.0
output application/xml
ns ns0 http://tempuri.org/
---
{
	ns0#Add: {
		ns0#intA: vars.var1 as Number,
		ns0#intB: vars.var2 as Number
	}
}
]]></ee:set-payload>
					</ee:message>
				</ee:transform>
		<choice doc:name="Choice" doc:id="9aed1cd0-f11e-44ba-93e1-b95d0a22ffa2" >
			<when expression="#[vars.operation=='add']">
				<wsc:consume doc:name="add" doc:id="3f71cbd8-7c83-432f-9dca-949f9545f77d" config-ref="Web_Service_Consumer_Config" operation="Add"/>
			</when>
			<when expression="#[vars.operation=='divide']">
				<wsc:consume doc:name="Divide" doc:id="fde17eab-4c99-4242-b3b0-72bf02e48f0a" config-ref="Web_Service_Consumer_Config" operation="Divide"/>
			</when>
			<when expression="#[vars.operation=='multiply']">
				<wsc:consume doc:name="Multiply" doc:id="18da7485-4651-46cd-8f04-bc9500448e13" config-ref="Web_Service_Consumer_Config" operation="Multiply"/>
			</when>
			<when expression="#[vars.operation=='subtract']">
				<wsc:consume doc:name="Subtract" doc:id="b8ca06e4-8612-45ee-99ad-4d480785d047" config-ref="Web_Service_Consumer_Config" operation="Subtract"/>
			</when>
			<otherwise >
				<set-payload value="Invalid Operation" doc:name="Set Payload" doc:id="f20c4877-0a1e-40b7-8b8f-b385f1d436bf" />
			</otherwise>
		</choice>
	</flow>
</mule>

Step 6: Hit the URL from postman to see the output we want.

 

Wrapping Up:

Consuming SOAP web service using MuleSoft is as easy as getting results from the web by searching anything. It is also a high security consumption of web service as we are using SOAP web service. Any MuleSoft Developer can use this flow to consume the SOAP web service using MuleSoft.

Find more MuleSoft best practices here at : https://www.caeliusconsulting.com/blogs/

Transforming messages with DataWeave

transforming messages with dataweave

DataWeave is an expression language designed by MuleSoft. The language helps in transforming the incoming payload to various payloads as per the requirements.  Most developers write transformation script in the transform message or set payload components. The language is tightly integrated with the Mule runtime engine and is a must-learn for every MuleSoft developer.

A few examples for transforming the input payload into various patterns:

Example 1: Given an array, we’ll generate the following output pattern using the input payload.

Input payload:

          [
	{"name": "Roger"	},
	{"name": "Michael"	},
	{"name": "Harris"	}
     ]

Required Output Pattern:

          [
  {
    "user 1": "Roger"
  }, 
  {
    "user 2": "Micheal"
  }, 
  {
    "user 3": "Harris"
  }
        ]

Expression Used to Transform:

%dw 2.0
output application/json
---
 
payload.name map ((item, index) ->
{
   ("user" ++" "++ index+1): item
})

 

Example 2: Given two arrays, [1,2,3,4,5,6,7] and [4,5,6,7,1], we’ll merge into a single array without duplicates, [1,2,3,4,5,6,7]:

Expression Used to Transform:

%dw 2.0
output application/json
var str = [1,2,3,4,5,6,7]
var str1= [4,5,6,7,1]
---
(str ++ str1) distinctBy ((item, index) ->item )

 

Example 3: From the object, we’ll remove the “last name” and “first name” key-value pair.

Input Payload :

{
        "first name": "Keith",
       "last name": "Peters",
        "age": 25
        
}

Required Output Pattern :

{
 "age": 25
}

Expression Used to Transform:

%dw 2.0
output application/json
---
payload filterObject ((value, key) ->
(key as String != "first name")
and key as String !="last name")

 

Example 4: From the array [1,2,3,’a’,’b’], remove 2 and b.

Expression Used to Transform:

%dw 2.0
output application/json
var arr = [1,2,3,'a','b']
---
arr-2-'b'

 

Example 5: Given the below JSON, transform all names to uppercase.

Input Payload :

    [
    {"name": "Roger"    },
    {"name": "Michael"   },
    {"name": "Harris"   }
    ]

Output Pattern:

[
 {
   "Name": "ROGER"
 },
 {
   "Name": "MICHAEL"
 },
 {
   "Name": "HARRIS"
 }
]

Expression Used to Transform:

%dw 2.0
output application/json
fun UpperCase(input_value)=upper(input_value)
---
payload map(item, index) ->
Name:UpperCase(item.name)

 

Example 6: Retrieve all the records of users with the age greater than 20.

Input Payload :

[
{
  "name": "Chris Jordan",
  "age": "19"
},
{
  "name": "Glenn Maxwell",
  "age": "24"
},
{
  "name": "Mike",
  "age": "20"
}
]

Expression Used to Transform:

%dw 2.0
output application/json
---
payload filter ((item, index) ->
item.age>20)

 

Example 7: Retrieve the average age of persons in the input payload.

Input Payload :

[
{
  "name": "Chris Jordan",
  "age": "19"
},
{
  "name": "Glenn Maxwell",
  "age": "24"
},
{
  "name": "Mike",
  "age": "20"
}
]

Expression Used to Transform:

%dw 2.0
output application/json
---
payload filter ((item, index) ->
item.age>20)
 

 

Example 8: Sort persons in payload according to age.

Input Payload:

[
{
  "name": "Chris Jordan",
  "age": "19"
},
{
  "name": "Glenn Maxwell",
  "age": "24"
},
{
  "name": "Mike",
  "age": "20"
}
]

Expression Used to Transform:

%dw 2.0
output application/json
---
payload orderBy ($.age)

[ If we want the data in descending order]

%dw 2.0
output application/json
---
payload orderBy (-$.age)

 

Example 9: Skip the null values from input payload

Input Payload :

[
{
  "name": "Chris Jordan",
  "age": null
},
{
  "name": "Glenn Maxwell",
  "age": "24"
},
{
  "name": "Lisa",
  "age": null
}
]

Expression Used to Transform:

%dw 2.0
output application/json
skipNullOn = 'everywhere'
---
payload

 

Example 10: Extract the file name from the input payload which is after “/”

{
   "filename":  "njnjnjnnjnbhbhjb/ui900jnnjn"
}

Expression Used to Transform:

%dw 2.0
output application/json
import * from dw::core::Strings
---
substringAfterLast(payload.filename,'/')

 

Example 11: Transform the present date and time to format like “yyyy-MM-dd HH:mm:ss.S”

Expression Used to Transform:

%dw 2.0
output application/json
---
now() as LocalDateTime as String {format: "yyyy-MM-dd HH:mm:ss.S"}
 

In all the above examples, we took the input payloads in JSON formats and tried to convert the inputs into the required patters using DataWeave.

Find more MuleSoft technical guides at Caelius Consulting Resource Centre.

 

 

 

 

 

 

API Groups in Anypoint Platform

API groups in Anypoint Platform

API Groups in Anypoint platform enables us to bundle our APIs and resources into a single package. We can customize the instances of that group with different SLAs and rate limit conditions based on the requirement and publish the API Group to Anypoint Exchange to subscribe to the package.

API groups can be versioned like APIs, published to exchange, and can include more than one instance of a single API.

To understand API groups better, let’s consider an online food delivery service like UberEats or Zomato; the service can have many different APIs like

  1. User API
  2. Restaurant location API
  3. Payments API
  4. Transaction API
  5. Rewards API and many more

These can be grouped into different packages like user-centric groups that can have User and Rewards API, and the financial group, which will include Payments and Transactions API.

Before we delve into and see how to create and manage an API group, there are a few prerequisites like

  1. At least two APIs deployed in the API manager.
  2. Permissions to create API Groups

Creating API groups

Navigate to API Manager > API Groups > click Create API group

Provide the group name and version. Add API to the group created.

API group add API

SLA Tiers for API groups

SLA (Service Level Agreement) can be applied to the API instances inside a group to limit the number of requests an application/user can make to the API.

To add an SLA tier to the API group, navigate to the API group instance > SLA Tiers > click Add SLA Tier

Add Group Add SLA

On the next screen, define the limit for SLA

API Group Add SLA

There are two SLA Tier types defined:

  1. Default SLA- The default limit applies to all API instances, existing or new. The same SLA limit applies to every API instance in that API Group.
  2. Individual SLA – Individual SLA is defined for each API within an API group. If defined, Individual SLA overrides the default SLA

 

After creating SLA, we need to apply SLA based policy at the API level. Next, head over to the API Administration page for the API, which is part of the API group > Policies > Click Apply New Policy > Rate Limiting- SLA Based.

Note: Applying Policy at API instance level is mandatory; otherwise, SLA tier will affect the API calls.

Once the policy application to the API, publish the API group to Exchange and request Access for the group.

API Group Request Access

Testing out the SLA Tier

Hit the API from the postman and observe the responses. After five hits, it will return 429 status, “too many requests”.

API Group Test

 

API groups help MuleSoft Developers achieving a greater agility. Find more technical guides on MuleSoft at Caelius Consulting Resource Center.

Standalone Runtime server in Mule 4

Standalone Runtime server in Mule

Why do we need a Standalone Runtime Server?

We can deploy our application on Anypoint studio. It has an embedded mule runtime server and we are deploying it on Anypoint studio. But in production, we won’t do that. We need to start standalone Mule Runtime.

How to start a Standalone Runtime Server?

  1. We need to download Mule Runtime Server from the link:  https://www.mulesoft.com/lp/dl/mule-esb-enterprise
  2. Extract the downloaded zip file in your root directory.
  3. Login to your Anypoint Platform -> Runtime Manager -> Servers -> Add Server

Runtime manager

4. Popup window will be displayed as shown below.

Runtime manager pop up

  1. Go to the directory where you have extracted your  Standalone Runtime zip. Go to the bin directory and open the command prompt.

command prompt

6. Execute the command that you have copied from the above popup window. You can replace the server name with the name that you want to give to a server. Remove (./ )from the command before executing the command. Mule runtime agent will get installed after executing the above command.

Mule Agent installer

  1. Once the mule runtime agent is installed, you will see the server with your given name is created in runtime manager with status CREATED.

Standalone Runtime server

8. Now, go to Applications ->Deploy Application

9. Upload the jar file and deploy the application.

Application Deployment

10. Check the application status.

Deploy Application

11. We can check the status of the application in the bat file.

BAT file

12. Now put a get request, and we would be able to get the results.

Runtime server results

13. Use ctrl+c in the mule bat file  to disconnect the application.

bat file final

This guide will help MuleSoft Developers gaining a better understanding of deploying a Standalone Runtime server. Thanks for reading. Find more MuleSoft best practices here at Caelius Consulting Resource Centre.