How to download CSV using REST API?

Viewed 24407

Here's a REST API that I am trying for downloading data as CSV file.

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

    var data = '\n'; // workaround to separate <xml> start tag on first line
    data += 'Firstname,Lastname,Username' + '\n';
    data += 'Nikhil,vartak,niksofteng' + '\n';
    data += 'Unknown,person,anonymous' + '\n';

    response.setHeader("Content-Disposition", "attachment;filename=Xyz.csv");
    response.setContentType("text/csv");
    response.setBody({'data':data});

})(request, response);

According to docs setBody requires a JS object and thus if I just pass data variable I get error stating that data cannot be parsed into ScriptableObject.

So with the current code I get below response:

{
  "result": {
    "data": "\nFirstname,Lastname,Username\nNikhil,vartak,niksofteng\nUnknown,person,anonymous\n"
  }
}

And the generated CSV looks like this:

enter image description here

Any idea how to get rid of that XML markup on 1st and 5th line?

1 Answers
Related