简体   繁体   中英

Is play! Framework 2.0 suitable for creating a REST API?

I have developed a REST API using Play! Framework 1.2.4, and I have a strong liking for the framework. The simplicity and the rapid development cycle helped me achieve this in a fraction of the time I would have taken had I gone the traditional Java EE route.

Now that I am exploring using Play! 2.0.3 for my next project. I see that while the framework has been enhanced and makes it even easier to develop web-apps , the same cannot be said about REST API's . My app will not have any HTML whatsoever - I will just respond with XML or JSON or whatever data exchange format I decide to use in future.

So, the question is:

Has anyone here used Play 2.0.x for exposing non-html pure REST API's?

More Details:

Here are some of the factors I feel make it more difficult to develop pure REST API's in Play 2.0.x compared to 1.2.x. Please correct my understanding if I am wrong.

Content Negotiation is harder

In play! 1.2.4, I content negotiation was build in to the framework. There were options to define right in the routes file what content-type a request expects.

GET /friends User.listFriends(format:'xml')

Then, in the controller,

public static void getFriends(){
    render();
}

This would result in the views/xml/User/listFriends.xml template being rendered automatically. To add support for JSON tomorrow, all I needed to do was to add a views/json/User/listFriends.json template.

I do not see how this can be done in play! 2.0.x

Creating non-html templates is less intuitive

After some trial and error, I figured out that one can create, for example, a listFriends.scala.xml in the views folder in play! 2.0. Then, it needs to be invoked in the controller code as follows:

return ok(views.xml.listFriends.render()) ;

However, Eclipse doesn't like this, because Eclipse does not know about the views.xml.listFriends since it is generated only after play compilation completes. Is there anything I'm missing here?

In Play (Scala) you can do something like this:

val myXMl = obtainXML();
return Ok(myXML).as("text/xml")

I'm not sure of the syntax in Java, but it would be equivalent: instead of creating a template, you generate the XML and then you send it to the user, setting the return type to "text/xml" (or json or whatever you need it to be).

As Pere Villega explained, but with the Java syntax:

String xml = getXMLAsString();
return ok(xml).as("text/xml");

The as() method is part of the Status class .

Or, an alternative is:

String xml = getXMLAsString();
response().setContentType("text/xml")
return ok(xml);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM