DEV Community

Cover image for Returning CSV Content From an API in Node.js
Antonello Zanini for Writech

Posted on • Originally published at writech.run

Returning CSV Content From an API in Node.js

Several systems and platforms allow you to import data from a CSV (Comma-Separated Values) file. This is because CSV is one of the most popular human-readable formats, especially regarding data science.

What generally happens is that you convert the data returned by an API or a query into a valid CSV file. This involves boilerplate code or manual work. Luckily, you can avoid all this.

This is because you can directly use Node.js to produce CSV as output, allowing users to download a CSV file. This is an automated and more practical solution.

Let's now learn how to build an API that returns CSV content in Node.js.

Prerequisites

You do not need any extra library to return CSV content to an Express server. At the same time, you could adopt the csv-generate npm library for making CSV generation easier.

You can install csv-generate with the following command:

npm instal csv-generate
Enter fullscreen mode Exit fullscreen mode

This is not required; here, you will see how to produce and return CSV content in Node.js without additional dependencies.

Building an API That Returns a CSV File in Node.js

The Content-Type HTTP header is used to specify the media type of the returned content. As described here, the recommended media type for an HTTP request that returns CSV is text/csv.

Also, you can use the Content-Disposition HTTP header to specify that the content returned by the API is an attachment that should be downloaded and saved locally.

You can set these two HTTP headers in Node.js as follows:

 res
    .set({
      "Content-Type": "text/csv",
      "Content-Disposition": `attachment; filename="<YOUR_FILE_NAME>.csv"`,
    })
Enter fullscreen mode Exit fullscreen mode

Replace <YOUR_FILE_NAME> with the name you want to give to the CSV file returned by the API.

Keep also in mind that CSV files are often very different. You may need to produce files with different delimiters, enclosing quotes, escaping characters, line separators, encodings, etc. Note that csv-generate allows you to customize the output format for your CSV file.

Now, let's see what an API that returns CSV content in Node.js looks like:

const express = require("express")
const app = express()

app.get("/users/getCSV", function (req, res) {
  // retrieving the user with a query...

  const users = [
    { name: "Patricia", surname: "Smith", age: null },
    { name: "John", surname: null, age: 56 },
    { name: "Maria", surname: "Brown", age: 37 },
  ]

  // initializing the CSV string content with the headers
  let csvData = ["name", "surname", "age"].join(",") + "\r\n"

  users.forEach((user) => {
    // populating the CSV content
    // and converting the null fields to ""
    csvData += [user.name, user.surname, user.age].join(",") + "\r\n"
  })

  // returning the CSV content via the "users.csv" file
  res
    .set({
      "Content-Type": "text/csv",
      "Content-Disposition": `attachment; filename="users.csv"`,
    })
    .send(csvData)
})
Enter fullscreen mode Exit fullscreen mode

For simplicity, the data used to generate the CSV content was hard-coded. You can generate this data in a real-world scenario by performing a query or calling an API.

Then, the csvData string variable is initialized with the CSV headers. This is not mandatory and depends on what you want your output content to look like. Also, the CSV content generated here uses the "," delimiter, but any other valid delimiter will do.

Note that the join() JavaScript function automatically converts null and undefined values into the "" empty string. This is exactly how null or missing content is represented in the CSV format.

Now, call the /users/getCSV API, and you will get the following content:

name,surname,age  
Patricia,Smith,  
John,,56  
Maria,Brown,37
Enter fullscreen mode Exit fullscreen mode

As you can see, the output generated by the API is valid CSV content. When called in the browser, the users.csv file will be automatically downloaded.

Et voilà! You just learned how to return CSV content in Node.js.

Conclusion

Returning CSV content from an API is much more efficient than retrieving the desired data and then converting it into the desired output. You can return a CSV file directly with Node.js. In this article, you learned how to achieve such a result in an Express server.

Thanks for reading! I hope you found this article helpful.


The post "Returning CSV Content From an API in Node.js" appeared first on Writech.

Top comments (0)