I was teaching an introduction to web development to a group of native desktop developers who have never, ever seen web development. They were familiar with object oriented programming and mainly worked with XML. During a section on REST, I mentioned that REST responses are sent as JSON. This lead to a discussion on what is JSON.
REST responses are based on the media-types set in the Accept header . These days we typically default to
application/json, but that doesn't mean that
text/xml isn't valid. It completely is! The recent prevalent use of single-page applications makes it easier to interoperate with
application/json, but it isn't the only media type.
The REST specification states that an end-point can support multiple media-types and must communicate which ones it can produce. Ten year's ago, I worked on a project that did this. There was one end-point that could respond with both
image/jpeg. This single end-point returned financial data as a JSON array, but if you set the
Accept header to
image/jpeg it would return you a line graph.
Under the hood, the implementation would respond with an object, but as the object was leaving the application, it would use an object mapper to map the response to either
image/jpeg based on the
The beauty and magic of this is the uniform interface constraint defined in REST. Through a single end-point, the same data can be represented in different media-types. This provides a single source of truth. Remembering this experience, it makes me wonder why we added such complexity to our front-end application?
Do we really need front-end graphing libraries, when this complexity can be moved and cached in the back-end? Even that experience from ten year's ago, did we really need
application/json. We could have just used
text/html to return the table and have CSS manage the presentation.
In the current landscape, data is converted to JSON which is then programmatically transformed into HTML or an image in the front-end. If a REST API is designed with a uniform interface, then it can respond with JSON, partial HTML fragments or an image. Not only would this simplify the front-end, but the performance would probably be better as no data transformation would be required on the front-end.
- Header image by Pacopac, CC BY-SA 4.0 https://creativecommons.org/licenses/by-sa/4.0, via Wikimedia Commons