Nikhil Vartak
Nikhil Vartak

Reputation: 5117

How to download CSV using REST API?

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?

Upvotes: 4

Views: 35304

Answers (1)

Silas
Silas

Reputation: 171

The setBody method expects a Javascript object which it is then going to serialize to JSON or XML based on what the client tells it do via Accept header.

In your case you want to produce your own serialized format: CSV. So instead of using the setBody method, use the stream writer interface to directly write to the response stream.

response.setContentType("text/csv");
response.setStatus(200);
var writer = response.getStreamWriter();

writer.write('Firstname,Lastname,Username\n');
writer.write('Nikhil,vartak,niksofteng\n');

etc.

Note you will have to handle all the details of CSV format yourself, including properly encoding any special characters like if you want a field to contain a comma like "Nik,hil".

Cheers,

Silas

Upvotes: 5

Related Questions