Issue
I have an RESTful API with controllers that should return a JSON response when is being hit by my android application and a "view" when it's being hit by a web browser. I'm not even sure I'm approaching this the right way. I'm using Laravel and this is what my controller looks like
class TablesController extends BaseController {
public function index()
{
$tables = Table::all();
return Response::json($tables);
}
}
I need something like this
class TablesController extends BaseController {
public function index()
{
$tables = Table::all();
if(beingCalledFromWebBrowser){
return View::make('table.index')->with('tables', $tables);
}else{ //Android
return Response::json($tables);
}
}
See how the responses differ from each other?
Solution
You can use Request::wantsJson()
like this:
if (Request::wantsJson()) {
// return JSON-formatted response
} else {
// return HTML response
}
Basically what Request::wantsJson()
does is that it checks whether the accept
header in the request is application/json
and return true or false based on that. That means you'll need to make sure your client sends an "accept: application/json" header too.
Note that my answer here does not determine whether "a request is coming from a REST API", but rather detects if the client requests for a JSON response. My answer should still be the way to do it though, because using REST API does not necessary means requiring JSON response. REST API may return XML, HTML, etc.
Reference to Laravel's Illuminate\Http\Request:
/**
* Determine if the current request is asking for JSON in return.
*
* @return bool
*/
public function wantsJson()
{
$acceptable = $this->getAcceptableContentTypes();
return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}
Answered By - Unnawut
Answer Checked By - Gilberto Lyons (JavaFixing Admin)