MuleSoft — Weaving a Multi-header CSV

Amlan Mahapatra
The Mule Blog
Published in
3 min readJun 1, 2020

Often in our projects we need to create a csv files. In this tutorial we will learn how to make a multi-header csv very easily using Mule’s functional programming Dataweave 2.0.

For this, we will use two api which will give us same json data:

  1. https://cat-fact.herokuapp.com/facts/random?animal_type=cat&amount=10

2. https://elephant-api.herokuapp.com/elephants

Step 1: Configure the http-request connector for “https://cat-fact.herokuapp.com/facts/random?animal_type=cat&amount=10

It will give a response like

But for this example, we don’t need to much field. So extract some field and make a csv and store it in a variable , named “catfact”. For that ,drag a transform message connector and change the target to variable and write this dataweave code.

In this example, we will use one three fields — createdAt, updatedAt, text.

The data of this variable will be like -

Step 2 : In same way we have to Configure the http-request connector for “https://elephant-api.herokuapp.com/elephants

In the same way, we have to set extract some data , convert the data in csv and store the data in variable, named “elephantfact”.

The data of the variable will be like -

Ok, our data is ready. Now we have to make a single csv file with these two variable.

Step 3: Add a header for second csv, means hear — “elephantfact”.

The problem with the csv file is it accepts only one row for header and you can’t change this feature. So if we merge these two csv data then the header of the second data will be removed automatically. Means in this example, the header of “elephantfact” will remove. Then it will be a single header csv file. But as per our requirement, we have to make a multi-header csv. So , just set a variable which will hold the header of the second csv means “elephantfact” and give a name — “elephantheader”, like -

Step 4 : Now merge these 3 variables

Step 5 : For testing purpose we can add a file write connector and store the csv file in local or sftp .

--

--

Amlan Mahapatra
The Mule Blog

Java| Spring-Hibernate | Certified Mulesoft Developer | Foodie | Nocturnal