RESTful APIs with Play Framework — Part 1

Mercedes Wyss
7 min readJan 11, 2018

--

During the last year I was in many conferences talking about “RESTful Services with Play Framework, and a Security Level with JWT”, an amazing experience that makes me want to share that with more people. I am writing a series of articles touching the aspects of my talk. We will start talking about the main Play Framework characteristics, how develop RESTful services and finally how add a security level using JWT.

Play Framework

“Play is based on a lightweight, stateless, web-friendly architecture. Built on Akka, Play provides predictable and minimal resource consumption (CPU, memory, threads) for highly-scalable applications.”

Programming Language
One of the secrets that makes Java a powerful programming language, is the JVM (Java Virtual Machine). This has led to develop programming languages more modern that run over it, like Kotlin, JRuby, Jython, Apache Groovy, Clojure, Scala. Play is developed on Scala, which allows us the versatility of using Java, Scala or both.

Resources Consumption

Resources Consumption
Something impressive about Play is the low resources consumption. The previous image shows the performance of the server’s CPU during stress tests. Those tests was made during a period of 3 hours, where up to 50 requests were sent simultaneously. The graphic show us that it was not used more than 17.5% of the CPU during the tests.

Now, answer this question. How many resources do you believe that have this server for can handle those tests?, well the server is an Amazon EC2 Instance, with OpenSuse, 1 CPU and 1GB of RAM. Really impressive.

Reactive Framework

Less Configurations
Play comes preconfigured with Akka since his version 2.6.x, in the last versions with Netty. That makes that we don’t need to configure an App Server in our development environments, and production, QA, and development servers.

JRebel Behavior
When we develop with Java, one of the more unpleasant things can be make redeploys everything when we want to test something. That process can be annoying, indeed when we make it with IDEs help, especially because that consumes time. With Play we only need to save our job an refresh for see our changes. I like to call that “More Code, and Less Deploys”

Start and Structure

For develop with Play Framework we need SBT, a build tool for Scala and Java. You can download it and see the configuration instructions in the oficial Web Site, You need to have install the Java JDK.

Creating a New Project
Once installed SBT, we can start. For create a new proyecto you can use one of the next commands:

run the next command for start a Java based project

$ sbt new playframework/play-java-seed.g8

Next, will request you basic information for the creation of the project, such as the name, the package, the version of Scala, Play and SBT to use. If you do not enter anything and only press return, it will put the default values.

This template generates a Play Java Projectname [play-java-seed]: PlayJava
organization [com.example]: com.auth0
scala_version [2.12.4]:
play_version [2.6.10]:
sbt_version [1.0.4]:
Template applied in ./PlayJava

run the next command for start a Scala based project

$ sbt new playframework/play-scala-seed.g8

Next, will request you basic information for the creation of the project, such as the name, the package, the version of Scala, Play and SBT to use. If you do not enter anything and only press return, it will put the default values.

This template generates a Play Scala Projectname [play-java-seed]: PlayScala
organization [com.example]: com.auth0
play_version [2.6.10]:
sbt_version [1.0.4]:
scalatestplusplay_version [3.1.2]:
Template applied in ./PlayScala

Making Deploy
For the purposes of this article we will use the Java project, nevertheless you can found in the GitHub repo the code for both Java and Scala.

For can make deploy we need to go inside the project’s directory, in this case playjava/

$ cd playjava/

Once inside the folder we execute the command sbt run, and will happen the next

$ sbt run[info] Loading settings from plugins.sbt,scaffold.sbt …
[info] Loading project definition from C:\Users\itrjwyss\Documents\PlayJava\project
[info] Loading settings from build.sbt …
[info] Set current project to java (in build file:/C:/Users/itrjwyss/Documents/PlayJava/)
— — (Running the application, auto-reloading is enabled) — -[info] p.c.s.AkkaHttpServer — Listening for HTTP on /0:0:0:0:0:0:0:0:9000(Server started, use Enter to stop and go back to the console…)

Now we can go to our browser or client to test RESTful services like Insomnia, and load http://localhost:9000

Voilà, Play is Running

Voilà, we have running our Play application. If you go to the console you will see

(Server started, use Enter to stop and go back to the console…)[info] p.a.h.EnabledFilters — Enabled Filters (see <https://www.playframework.com/documentation/latest/Filters>):play.filters.csrf.CSRFFilter
play.filters.headers.SecurityHeadersFilter
play.filters.hosts.AllowedHostsFilter
[info] play.api.Play — Application started (Dev)

Everything you see in the console is recorded in the Play logs file.

Basic Structure

Basic Project Structure
  • app: in this directory will have all our source code (controllers/) and our html templates (views/).
  • conf: in this directory are the configuration files for our Play application.
  • logs: in this directory you will find the Play’s logs file.
  • project: in this directory you will find the SBT’s configuration files.
  • public: static assets directory, like images, css style files, and javascript files.
  • test: Sources to be able to carry out unit tests. Play is based on JUnit to perform this action.

Now let’s see a bit of the general syntax that Play handles. The first files that we will visit will be those located in the app/views/ directory, there we have two files the main.scala.html and index.scala.html.

See first main.scala.html

@*
* This template is called from the `index` template. This template
* handles the rendering of the page header and body tags. It takes
* two arguments, a `String` for the title of the page and an `Html`
* object to insert into the body of the page.
*@
@(title: String)(content: Html)
<!DOCTYPE html>
<html lang=”en”>
<head>
@* Here’s where we render the page title `String`. *@
<title>@title</title>
<link rel=”stylesheet” media=”screen” href=”@routes.Assets.versioned(“stylesheets/main.css”)”>
<link rel=”shortcut icon” type=”image/png” href=”@routes.Assets.versioned(“images/favicon.png”)”>
</head>
<body>
@* And here’s where we render the `Html` object containing
* the page content. *@
@content
<script src=”@routes.Assets.versioned(“javascripts/main.js”)” type=”text/javascript”></script>
</body>
</html>

And now see index.scala.html

@()@main(“Welcome to Play”) {
<h1>Welcome to Play!</h1>
}

One of the virtues of Play in terms of Frontend development that is worth mentioning, although that is not the objective of those series of articles, is the inheritance between templates. In this case, index.scala.html inherits from main.scala.html. Much of the magic of its html syntax occurs with @, we can notice that it uses it for comments, insert blocks of code, define receive parameters and even inheritance as can be seen with @main () in index.scala.html, this indicates that index inherits from the main template. In main we can see the @content, which indicates that there will be inserted the html code, in this case index.

Let’s continue to see the structure of a Controller, the place where all the magic happens. Play is based on the MVC model, the Models are DB’s admin structures, the Views our html templates, and the controllers, well Play Controllers. Another important aspect of Play is that RESTful is a first citizen, so everything is a RESTful, the controllers are in the app/controllers/ directory.

package controllers;import play.mvc.Controller;
import play.mvc.Result;
/**
* This controller contains an action to handle HTTP requests
* to the application’s home page.
*/
public class HomeController extends Controller { /**
* An action that renders an HTML page with a welcome message.
* The configuration in the <code>routes</code> file means that
* this method will be called when the application receives a
* <code>GET</code> request with a path of <code>/</code>.
*/
public Result index() {
return ok(views.html.index.render());
}
}

Play works through Actions, an action is just a method in charge of processing Request’s Parameters and producing a Result that will be sent to the client. Therefore, it is the implementation of a WS RESTful. On the other hand, a Controller is nothing more than a class that inherits from play.mvc.Controller and is responsible for managing a set of actions.

To finish with the structure of a Play project that we must control, we will talk about how the routes are handled, for this we will explore the routes file in the conf/ directory.

routes

# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# An example controller showing a sample home page
GET / controllers.HomeController.index
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.versioned(path=”/public”, file: Asset)

The syntax of the routes file is in Scala, here we can include comments with #, the next is the structure of the routes. The first thing we must indicate is the http method that we will use (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS) or we can use * to indicate that it can be consumed by any of the methods.

The next thing to indicate, is how the action will be called, this name will be added to our domain. For example, if our domain were auth0.com and we had a definition like the following

GET     /pathExample

This action would be call: auth0.com/pathExample

Finally, we must indicate to what action this route will redirect. For this example, assume that within our Controller HomeController we have the pathExample action, so the final route would look like this:

GET     /pathExample         controllers.HomeController.pathExample

In this article we have covered basic aspects about Play. Wait for the next series of this articles, when we will talk about develop RESTful Services.

--

--

Mercedes Wyss

Full Stack Developer, CTO at #Produactivity, @Auth0 Ambassador, @JDuchess #GT and @502Devs Community Leader. Duke’s Choice Award