Create a multipart/form-data request using MuleSoft DataWeave

Calling APIs from MuleSoft is an easy process using the HTTP Connector and DataWeave. The connector gives you the ability to send requests to HTTP services and handle their response within your application flow and DataWeave gives you the ability to create the requests that need to be passed to the HTTP services in the appropriate format.

I recently ran into a use case where I figured it might help to write an article about using the HTTP Connector and DataWeave to help others that faced the same issue. A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server. The question was how to create the multipart/form-data request that needed to be passed to the endpoint.

It involves making a POST request using the multipart/form-data type and constructing it using DataWeave. If you’ve used Postman, you’ve probably seen the cURL request below before in the screenshot. Lines 13-15 are the form fields that need to be passed to a server.

The configuration of the HTTP Request is pretty standard. Of course you’ll set the “Method:” field to be a POST request. And the Body can stay as the default payload variable.

The Transform Data component that you place before the HTTP Request is where you’ll create the multipart/form-data request that will be passed in as the payload.

In the Transform Data component, you can see an example of the code below. Set the output to multipart/form-data and then construct the script accordingly. The “parts” field is required and then each item consists of the field name (e.g. organizationId) which encapsulates “headers” and “content” fields.

%dw 2.0
output multipart/form-data
---
{
	parts: {
		organizationId: {
			headers : {
                            "Content-Type": "text/plain"
                        },
                        content: vars.organizationId
		},
		groupId: {
			headers : {
                             "Content-Type": "text/plain"
                         },
                        content: vars.organizationId
		},
		name: {
			headers : {
                             "Content-Type": "text/plain"
                        },
                        content: "Test API"
		}
	}
}

Here’s a screenshot of the Transform Component and the preview of the output from the script:

Hopefully this post helps by providing an example of what a cURL request looks like compared to the DataWeave script that builds the request.

You can read more about handling multipart form-data using DataWeave through this link. If you have any questions or run into any issues, please leave a comment!


Posted

in

by

Tags:

Comments