Rest – Returning view code in an API response

apiapi-designrest

I have an API that returns a JSON formatted array of users within a given pair of lat/ long bounds.

I'm using this data to plot a number of markers on a map, based on the location of each user.
I also want to render a HTML list on each client request so that I can show the list of plotted users alongside the map.

What is the best way to get the list HTML to the client?

To me it seems like an incorrect solution to return the HTML for the user list within the initial API call (response.html, or something), although this feels like I'm shoe-horning functionality into an otherwise clean API response.

I also don't want to make two API calls (one for the initial data and one for the HTML), for obvious reasons (overhead).

Finally, I don't want to generate the HTML client-side (in JavaScript), as I already have a class to do this for me server-side.

What options does that leave me with?

Thanks

Best Answer

Return the data for the list and use client side templating to convert it into HTML.

GET http://yourwebserver.com/users.json

[{ name: 'foo'}]

using a Mustache.js template like this

Mustache.render('<ul>{{#.}}<li>{{name}}</li>{{/.}}</ul>', data)

With this aproach you have a simple interface, reduce data transfer, and make the template static therefore cachable.

Related Topic