Desktop version

Home arrow Computer Science arrow Building Applications with Scala


Creating our API with REST and JSON

Alright, now is the time to design a REST API for your Play framework application. We will create an API to export all data in the system. This API will be READ only; however, you can add write operations if you like.

Later on in this chapter, we will add some back pressure to limit the API REST rate for consumers and create a Scala client application for our REST API. So, first of all, let's get started with the Play framework (server) first.

We don't need any extra library in order to create a REST API in our Play framework application. We will just need a new controller and new routes. Additionally, we will leverage most of the code we made in the previous chapters.


Let's create a new controller located at ReactiveWebStore/app/controllers.

REST API Front Controller implementation

RestApiController.scala file should look something like this:

package controllers @Singleton

class RestAPIController @Inject()

(val productService:IProductService, val reviewService:IReviewService, val imageService:IImageService) extends Controller { import play.api.libs.concurrent.Execution. Implicits.defaultContext def listAllProducts = Action {

val future = productService.findAll() val products = Awaits.get(5,future) val json = ProductsJson.toJson(products)



def listAllReviews = Action {

val future = reviewService.findAll() val reviews = Awaits.get(5,future) val json = ReviewsJson.toJson(reviews)



def processImages = { val future = imageService.findAll() val images = Awaits.get(5,future) val json = ImagesJson.toJson(images) json


def listAllImages = Action {




Basically, we have three functions here. These functions list all products, images, and reviews. As you can see at the top of the controller, we are injecting the three services that we have for products, images, and reviews.

The code is pretty much straightforward for all functions. First, we will call the proper service, and then we will wait for the result with the await object. Once we have the data, we will call a function to convert the data to JSON.

Let's take a look at the JSON helpers objects that we used here.

Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >

Related topics