Over a million developers have joined DZone.

Play in Action – Building REST Services

Using the Play framework to create controllers and REST services.

Learn how API management supports better integration in Achieving Enterprise Agility with Microservices and API Management, brought to you in partnership with 3scale

Play Framework - Build Modern & Scalable Web Apps with Java and Scala

In this article, we will try to build REST services. To build REST services, first we need to create a controller and actions. In Play we can create controllers by extending play.mvc.Controller. The methods in the controller which will take user requests are called as “actions”. The action method signature is shown below:

public Result <action_name> (parameters)

Here, action returns play.mvc.Result. Play has implementations for Result, which we can return from the action method. Below are the out of the box implementations for Result:

ok --> HTTP status code is 200
notFound --> HTTP status code is 404 
badRequest --> HTTP status code is 400 
internalServerError --> HTTP status code is 500 
movedPermanently 301 --> HTTP status code is 301 
found  --> HTTP status code is 302
temporaryRedirect--> HTTP status code is 307
forbidden--> HTTP status code is 403
status --> Developer can return any HTTP status code

Now, we will see a different implementation of actions:

Image title

The routes file entry is given below:

Image title

We can send query parameters to the action. The implementation is explained below:

Image title

The routes file entry is given below:

Image title

Now, we will see how the POST action is implemented:

Image title

Now, let us see the routes file entry to handle the above request:

Image title

The source code created to explain the above example is available on GitHub. In an upcoming article we will see how to integrate Play with MySQL. Till then, "Stay Hungry To Learn".

Play REST Services

Unleash the power of your APIs with future-proof API management - Create your account and start your free trial today, brought to you in partnership with 3scale.

Topics:
play framework ,activator ,typesafe

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}