WebAPI – Returning Data in a Non-JSON Format
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:
- To return data in JSON, the default format, the consumer would simply send a GET request to http://someurl.com/api/v1/bigdump
- To return data in buffered CSV, append ‘?format=csv’ as a querystring parameter
- 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.
Shri Bhupathi View All →
Husband, father, and consultant who dabs mostly in Microsoft technologies. Loves tennis – both watching and playing.