Best Practices for Returning JSON in a REST Application – PHP and Laravel Guide

apijsonlaravelPHPrest

I'm starting now with REST (using Laravel 4.2) and Mobile (Android, iOS, SP, etc.) applications.

Initially I'm checking if the request is ajax/json and then return a json response.

But this condition is in a normal action (HTTP), so:

if ajax/json return json, else return the view/template/layout

Is it correct to do that in the same action, or is the best practice to create another controller for that? For example:

  • PostsController
  • PostsMobileController

Or

  • PostsController
  • Mobile\PostsController (or Json\Controller) – using namespaces

Best Answer

Although the right solution depends on your context, here is my approach:

When designing classes one should always consider their single responsibility. In case of the PostsController it could probably be described "create, read update and delete" posts. Formatting of the output is a global problem of your application that should not be solved individually in each controller. Better would be to design this as an output strategy / aspect / whatever your language and framework allows.

Just imagine if you need an API for outputting XML at some time. Would you really create new controllers for each entity?

Btw, when considering such questions (for any language) I tend to look at the Rails documentation, which has a nice approach here:

class UsersController < ApplicationController
  def index
    # Load all users
    @users = User.all
    # Different formattings based on request headers
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render xml: @users}
      format.json { render json: @users}
    end
  end
end