11

How do I use play to develop webservice?

I cannot find any documents in the official site.

Codemwnci
  • 54,176
  • 10
  • 96
  • 129
LionPlayer
  • 119
  • 1
  • 1
  • 3
  • Why would you want to? Play is not a web-service framework, why would you want to use it for that? – skaffman Dec 22 '10 at 19:22
  • 6
    Play is actually very competent at building web services due to its strict RESTful nature, and the MVC pattern it employs makes it pretty simple to achieve. An example of why you would want to use a web application framework for Webservices, is for building web applications that also contain web services (such as twitter and its APIs). – Codemwnci Dec 22 '10 at 19:47
  • @LionPlayer have you had any luck with this ....i'm trying to do something similar. – Asif Mohammed Sep 07 '11 at 23:48
  • http://www.imind.eu/web/2013/11/07/developing-soap-services-using-play-framework-2-2-x/ – Andrzej Jozwik Jun 23 '14 at 08:28

1 Answers1

26

Quite simple really.

Play comes with a number of methods that you can use to expose your actions as web services.

For example

render()
renderJSON()
renderXML()

These can all be used to render data in a particular way.

If you had a web service, let's assume a RESTful webservice, that you wanted to return the sum of two numbers, you could do so in the following way

public class Application extends Controller {

    public static void sum(Float num1, Float num2) {
        Float result = num1 * num2;
        render(result);
    }
}

if your route is set up to use XML as the format, or the format is set correctly in the request header, you then return the result using a normal groovy template called app/views/Application/sum.xml

To setup the route to format correctly, then add the following line to your route file

GET /webservices/sum                 Application.sum(format:'xml')

The sum.xml would then look something like

<response>
  <sum>${result}</sum>
</response>

The same concept works for JSON.

If however you don't want to use groovy templates, you could simply create the XML or JSON using the renderJSON / renderXML methods, but this does mean you are building presentation logic into your controller, which is bad practice.

As a subnote, if you want to consume webservices, then you use the play.libs.WS class. I have written a blog on how to do that

http://playframework.wordpress.com/2010/08/15/web-services-using-play/

Codemwnci
  • 54,176
  • 10
  • 96
  • 129
  • It would be very helpful if you could update your answer to consider Play2.0 and Scala. I'll create that as a separate question – Jack Jan 06 '12 at 08:00
  • http://stackoverflow.com/questions/12180475/play-framework-webservice-tutorial-scala – Marouane Lakhal Nov 06 '15 at 07:26