Laravel return json or view - json

I'm developing an API where if the user specifies the action with .json as a suffix (e.g. admin/users.json), they get the response in the return of json, otherwise they get a regular html View.
Some actions may not have a json response, in which case they would just return a html View.
Does anyone have advice on how this can be implemented cleanly? I was hoping it could be achieved via the routing.

I suggest you to create your application as an api.
Foreach page, you need two controllers. Each controller use a different route (in your case, one route ending by .json, and one without).
The json controller return data in json form. The "normal" controller call the corresponding json route, deserialize the json, then pass the resulting array to the view.
This way, you've got a standardized api (and maintained, because your own app use it) available, as well as a "normal" website.
More information:
Consuming my own Laravel API
Edit: Maybe it's doable with a filter, but I'm not sure about that and I don't have time to try it myself right now.

In Laravel 5.x, to implement both capabilities like sending data for AJAX or JSON request and otherwise returning view template for others, all you have to do is check $request->ajax() or $request->isJson().
public function controllerMethod(Request $request)
{
if ($request->ajax() || $request->isJson()) {
//Get data from your Model or whatever
return $data;
} else {
return view('myView.index');
}
}

Related

Returning XML and Json formatted data from MVC controller

I need to create an MVC 4 controller that can return the same data either in a JSON format for an XML format depending on the request from the view. Would it be better to create two controllers or can this be done with one controller? If it can be done with one controller, can someone show me how this is done?
THanks.
You can certainly have add an Action to your existing controller that will return a JSON object as the result; luckily MVC has a nice, built-in way of returning JSON:
public JsonResult MyJsonAction()
{
var result = "my data";
return Json(result);
}
As for returning XML, there seems to be some useful answers on this question

Return JSON Result from an Api Controller

I'm building an Api Controller and I need to serialize my List to JSON as my action result.but It seems that such statements doesn't work
return Json(data, JsonRequestBehavior.AllowGet);
How can I achieve this ?
As you mentioned that you are using WEB API, I'm assuming it has the JsonFormatter configured. With that said, the responsibility to convert you action result into a JSON is not of your action but from the Media Type Formatter chosen as part of the Content Negotiation process.
That said, it's enough for your Action to return the actual List type and the Web API Media Type formatter will take care of formatting it to JSON.
For example, let's say that data is a List<Foo> where Foo is some type that you created. It is enough for your controller action to be:
public List<Foo> GetFoo()
{
var data = GetListOfFoo();
return data;
}
Have you tried using a JSON serializtion class?
I have had success using the ideas put forward in this article:
Serializing a list to JSON
Or, if you don't want to use serialization, the example for an action result using JSON in MSDN just uses a generic list object.

Pass Json Object from Play! framework to HighCharts JS

http://www.playframework.com/documentation/2.1.x/JavaTodoList
Using the above tutorial as a reference, I have created an application which sends data from the model to view via the Application controller.
I have managed to display the model(Tasks) as a high chart. The code is here.
public static Result format(){
return ok(views.html.frmt.render("Visualize it",Task.all()));
}
This goes to this view page.
http://ideone.com/ycz9ko
Currently, I use scala templating inside the javascript code itself. Refer to lines 9-14 and lines 20-24.This unelegant style of doing things is not really optimal.
I want to be able to accomplish the above using Json instead.
public static Result jsonIt(){
List<Task> tasks = Task.all();
return ok(Json.toJson(tasks));
}
My Qns are how to send the JSON objects to a view template.
And how to parse it into a Highcharts format. Is there some standard procedure to do this ? Or else I have to write my own method to do this ?
It'll great if someone can show me a code snippet. Also I would prefer a post not using Ajax. I would just want to know how to do this first.
I also found this stackoverflow post useful.how to parse json into highcharts. However, it didnt answer the part about converting from Play format to Highcharts format.
Thanks in advance
You don't need to pass a json object to your template, instead you might do an ajax call from your client side javascript (your template) and get json response that you could use futher in javascript code to build a chart. For example :
You have some path that is bind to your controller jsonIt() like so /chartsdata/json
then using jquery shorthand for ajax request:
var chart_data = $.get('/chartsdata/json', function(data) {
return data;
});
now you can use a chart_data that is an array of objects where each object represents a Task, in your further javascript code to build a chart.

Preventing default views with RESTful api in CakePHP

I am following the tutorial in the CakePHP book that explains the basics of setting up a RESTful web service.
So far, I've updated my routes file to the following:
Router::mapResources('stores');
Router::parseExtensions('json');
I have also setup a blank layout in app/layouts/json and the appropriate json views. I am receiving my json output successfully when I navigate to controller/action.json
I am wondering though, without the.json extension it attempts to load the regular view. I am looking to build a pure api with only json output, is there any way to prevent regular render output instead?
You could force a rendering as JSON if you can recognise a JSON request another way. For example, if the Accepts HTTP header contains application/json, you could put this in your controller:
public function beforeFilter(){
if ($this->request->accepts('application/json')) {
$this->RequestHandler->renderAs($this, 'json');
}
parent::beforeFilter();
}
It's CakePHP 2.0 notation, but something similar probably exists for CakePHP 1.2 and 1.3.
You could also detect the request Content-Type instead, or as well, especially if Accepts is not used.
What are you seeing at the moment? If you've used bake Cake may have generated the views for you?
Just delete the views in /app/views/layout and /app/views/controllername
If you are trying to prevent the request from hitting the controller at all then I'm not so sure, you could just update your .htaccess file to only send requests ending in .json to the app or something similar.
here is what i did.
if i know i'm building only json API, i added to my AppController.php following:
public function beforeFilter()
{
if (empty($this->request->params['ext']) || $this->request->params['ext'] != "json")
{
$this->render(FALSE, 'maintenance'); //no view, only layout
$this->response->send();
$this->_stop();
}
}
and in my /app/Layouts/maintenance.ctp
echo __('Invalid extension');
this way all requests without the json extension will end up on the "maintenance" page where you can put any info you want, i'm planning to put there link to API docs.

Rendering Views as String with Spring MVC and Apache Tiles

I am trying to reuse some of my tiles in a controller which is returning a json response to the client. I would like to return a json response similar to the following format:
{
'success': <true or false>,
'response': <the contents of an apache tile>
}
In my controller I would like to perform logic similar to this pseudocode:
boolean valid = validator.validate(modelObj)
String response = ""
if(valid){
response = successView.render() // im looking for a way to actually accomplish
// this, where the successView is the apache tiles view.
// I would also need to pass a model map to the view somehow.
}else{
response = errorView.render()
}
writeJsonResponse(httpResponse, /* a Map whose json representation looks like the one I described above. */)
I belive that you want to implement a view class that will wrap the output of a jsp in json. The class in question may be org.springframework.web.servlet.view.tiles2.TilesView.
Another option may be to extend the JSON converter. org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
If you need to render the view using Apache Tiles 2, you must use
org.springframework.web.servlet.view.tiles2.TilesViewResolver
See the example tutorial here: http://krams915.blogspot.com/2010/12/spring-mvc-3-tiles-2-integration.html
If you need to render the response as JSON, you can use the #ResponseBody which requires Jackson in your classpath. See the example here http://krams915.blogspot.com/2011/01/spring-mvc-3-and-jquery-integration.html (The controller returns JSON). You can also see a similar example of the #ResponseBody at http://krams915.blogspot.com/2010/12/jqgrid-and-spring-3-mvc-integration.html