Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC naming conventions for JSON actions

What naming convention is recommended when writing an MVC app that has both front-end and JSON paths to the required data?

For example, let's say the user of your site has "Things". They should be able to go to a page to view their things, but we also need a way to pull those things back as JSON on other pages. I've been able to think of several options but I'm not keen enough on any of them to proceed. Here's what I've got:

  1. /things/list for UI, /json/things for JSON - this would require a JsonController which would end up serving different kinds of objects, thereby defeating any chance of entity separation before we even start.
  2. /things/list for UI, /things/list/json for JSON - probably my preferred option at the moment, but requires magic stringing (albeit just "json"). Also, if you also need a (string id) action signature for taking in some filter parameters or such, then you have the choice of adding an extra route or doing some dirty string splitting.
  3. /account/mythings for UI, /things/list for JSON - a bit cleaner, but there might not always be a relevant controller that you could serve the "things" from. Plus, you're mixing entities again.

All and any suggestions welcome, thanks!

like image 554
tags2k Avatar asked Jun 06 '09 11:06

tags2k


1 Answers

Arguably the path names could all be the same. You can examine the Accept header for the mime-type of your client's desired response, and then return an appropriate view based on what you find there:

  • application/json: JSON View
  • text/xml: XML View
  • text/plain, text/html: JSP View

Browsers set this field to HTML; your JSON clients would simply set this field as appropriate.

like image 173
Peter Bratton Avatar answered Sep 20 '22 00:09

Peter Bratton