Search code examples
curlgroovymule-componentmulesoftmule4

how to call curl command from mule4


I have to upload a file to an API. I have the curl command for it and I am able to load through postman successfully. But now I want to call this curl command through MuleSoft? how can we do it? I tried through Execute component (through Groovy engine).But the file is getting loaded and there is no error also in the console log.

CURL COMMAND curl -H "apiAccessKeyId:USERNAME" -H "apiSecretAccessKey:PASSWORD" -H "Accept:application/json" --form "file=@C:\Files\medialist.csv" --form "params={Type:Import}" -X POST http://mysuperserver/media/upload/

Suggestions please?


Solution

  • You should not try to execute the curl command from the Mule application. I strongly discourage of doing that. Instead you should use Mule components and connectors to reproduce the same requests.

    For this specific situation you can use the File connector to read the file, a DataWeave transform to generate the multipart form data request with the attachment, and the the HTTP Request connector to send the same request and reproduce the same HTTP Request that curl performs.

    For example it would look similar to this in the XML view:

        <flow name="so-file-http-request-sendFlow">
            <file:read doc:name="Read" path="c:\files\medialist.csv"/>
            <ee:transform doc:name="Transform Message">
                <ee:message >
                    <ee:set-payload ><![CDATA[%dw 2.0
    output multipart/form-data
    ---
    {
        parts : {
            params : {
              headers : {
                "Content-Type": "text/plain"
              },
              content : "{Type=import}"
            },
            file : {
                  headers : {
                    "Content-Disposition" : {
                        "name": "file",
                        "filename": "medialist.csv"
                    },
                    "Content-Type" : "application/csv"
                  }     
                }
            }      
    }]]></ee:set-payload>
                </ee:message>
            </ee:transform>
            <http:request method="POST" doc:name="Request" config-ref="HTTP_Request_configuration" path="/media/upload/">
                <http:headers ><![CDATA[#[output application/java
    ---
    {
        Accept : "application/json",
        apiAccessKeyId : "USERNAME",
        apiSecretAccessKey : "PASSWORD"
    }]]]></http:headers>
            </http:request>
        </flow>
    

    You can use the HTTP wire logging to see if the request matches what CURL sends.