For Each Scope in Mule

For Each Scope in Mule

The For Each scope splits a payload into elements and processes them one by one through the components that you place in the scope. It is similar to a for-each/for loop code block in most programming languages and can process any collection, including lists and arrays. The collection can be any supported content type, such as application/json, application/java, or application/xml.

General considerations about the For Each scope:

By default, For Each tries to split the payload. If the payload is a simple Java collection, the For Each scope can split it without any configuration. The payload inside the For Each scope is each of the split elements. Attributes within the original message are ignored because they are related to the entire message.

For Each does not modify the current payload. The output payload is the same as the input.

For non-Java collections, such as XML or JSON, use a Dataweave expression to split data. Use the Collection field for this purpose.

The For Each scope stores each item of the collection in payload during each iteration.

You can also split an array into batches to enable quicker processing. Each batch is treated as a separate Mule message. For example, if a collection has 200 elements and you set Batch Size to 50, the For Each scope iteratively processes 4 batches of 50 elements, each as a separate Mule message.

flow for For Each scope :

for each scope configuration :

URL : http://localhost:8085/api/foreach
Method : POST

 Input : 

Output : 

XML project code :

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:json="" xmlns:http="" xmlns="" xmlns:doc=""
    <http:listener-config name="HTTP_Listener_Configuration" host="" port="8085" basePath="/api" doc:name="HTTP Listener Configuration"/>
    <flow name="test_foreachFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/foreach" doc:name="HTTP"/>
        <byte-array-to-string-transformer doc:name="Byte Array to String"/>
        <json:json-to-object-transformer returnClass="java.util.Map" doc:name="JSON to Object"/>
        <foreach doc:name="For Each">
            <logger message="#[payload]" level="INFO" doc:name="Logger"/>