WebAPI – Returning Data in a Non-JSON Format

Embed from Getty Images

A requirement recently emerged for an endpoint on a REST service to return a large block of data to be consumed by MATHLAB, Python, and Excel on the desktop. The REST Service is built on ASP.NET Core RC2.

Although JSON can be quite helpful in a couple of scenarios, the sheer amount of data and complexity of integrating JSON-data into Excel was a bit of a challenge and involved adding moving parts (more code outside the server-boundary, portability, maintenance, etc.). It was concluded that allowing the same endpoint to return data in either JSON (default), buffered CSV, or a CSV file based on a querystring would be the most user-friendly implementation; the pattern is already in use with other packaged vendor products within the firm.

The solution would look like this:

  1. To return data in JSON, the default format, the consumer would simply send a GET request to http://someurl.com/api/v1/bigdump
  2. To return data in buffered CSV, append ‘?format=csv’ as a querystring parameter
  3. And to return a CSV file, append ‘?format=csvfile’ instead

Here’s how you add this functionality in the controller method:

var data = DataServices.GetAll(requestorCtx);

if (Request.QueryString.HasValue) {
    if (Request.QueryString.Value.Contains("format=csvfile")) {
        return File(Encoding.ASCII.GetBytes(FormattersFactory.FormatThis(data)), "application/octet-stream", "largeblob.csv"); // Use this to return a file.

    if (Request.QueryString.Value.Contains("format=csv")) {
        return Content(FormattersFactory.FormatThis(data), new MediaTypeHeaderValue("text/javascript")); // Returns a stream.

    return BadRequest("Invalid format requested. Supported formats are 'csv' and 'csvfile'");

That’s it. The FormattersFactory in the above sample is a simple factory implementation to format data.

Notes from the field

Shri Bhupathi View All →

Husband, father, and consultant who dabs mostly in Microsoft technologies. Loves tennis – both watching and playing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: