Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

RESTful APIs With the Play Framework - Part 1

DZone's Guide to

RESTful APIs With the Play Framework - Part 1

In this article, we look at how to set up your development environment using the Play framework, and how to get Play going on your machine.

· Integration Zone ·
Free Resource

The Future of Enterprise Integration: Learn how organizations are re-architecting their integration strategy with data-driven app integration for true digital transformation.

Image title

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 to develop RESTful services, and finally how to 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." - Play Framework Documentation

Programming Language

One of the things that makes Java a powerful programming language is the JVM (Java Virtual Machine). This has led to developing programming languages more modern that run over it, like Kotlin, JRuby, Jython, Apache Groovy, Clojure, Scala, etc. 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 were conducted over a period of 3 hours, where up to 50 requests were sent simultaneously. The graphic shows 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

Fewer Configurations 

Play has come preconfigured with Akka since version 2.6.x, and, in the lastest versions, with Netty. That means 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 redeploying everything when we want to test something. That process can be annoying, indeed, when we make it with an IDE's help, especially because that consumes time. With Play, we only need to save our job and refresh to see our changes. I like to call that "More Code, and Less Deploys."

Start and Structure

For developing with the Play Framework, we need SBT, a build tool for Scala and Java. You can download it and see the configuration instructions on the official website. You also need to have installed the Java JDK.

Creating a New Project

Once SBT is installed, we can start. To create a new project, you can use one of the follwoing  commands:

Command to start a Java-based project:
$ sbt new playframework/play-java-seed.g8 

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

This template generates a Play Java Project

name [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

Command to start a Scala-based project:

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

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

This template generates a Play Scala Project

name [play-java-seed]: PlayScala
organization [com.example]: com.auth0
play_version [2.6.10]:
sbt_version [1.0.4]:
scalatestplusplay_version [2.12.4]:

Template applied in ./PlayScala

Building Your Deploy

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

To make our 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:

$ 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 the following:

(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 Play's log files.
  • project: In this directory, you will find SBT's configuration files.
  • public: A static assets directory, like images, CSS style files, and javascript files.
  • test: Sources to carry out unit tests. Play is based on JUnit to perform this functionality.

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: main.scala.html and index.scala.html.

First, let's look at 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, index.scala.html:

@()

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

One of the virtues of Play in terms of front-end development that is worth mentioning, although that is not the objective of this article, 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.scala.html we can see @content, which indicates that what will be inserted into the HTML code, in this case, it's an 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 are HTML templates, and the controllers, well, are Play Controllers. Another important aspect of Play is that RESTful is a first-class citizen, so everything is RESTful, the controllers are in the app/controllers/ directory.

HomeController.java

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 Parameters and producing a Result that will be sent to the client. Therefore, it is the implementation of a WS RESTful action. 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, we will talk about how the routes are handled, and, for this, we will explore the routes file in the conf/ directory.

# 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, so 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 what the action will be called. This name will be added to our domain. For example, if our domain were example.com and we had a definition like the following:

GET     /pathExample

This action would be call: example.com /pathExample

Finally, we must indicate to which action this route will redirect us. 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 of Play. In the next article of this series, we will talk about developing RESTful Services.

Make your mark on the industry’s leading annual report. Fill out the State of API Integration 2019 Survey and receive $25 to the Cloud Elements store.

Topics:
play framework ,scala ,reactive systems ,integration

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}