REST API with Play Framework

Ponshriharini
featurepreneur
Published in
3 min readMar 12, 2022

Play Framework makes it easy to build web applications with Java & Scala. Play is based on a lightweight, stateless, web-friendly architecture

Setting up REST API with Play Framework:

First, we’ll have to install SBT in order to start our application in the future.

echo "deb https://repo.scala-sbt.org/scalasbt/debian all main" | sudo tee /etc/apt/sources.list.d/sbt.list
echo "deb https://repo.scala-sbt.org/scalasbt/debian /" | sudo tee /etc/apt/sources.list.d/sbt_old.list
curl -sL "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x2EE0EA64E40A89B84B2DF73499E82A75642AC823" | sudo apt-key add
sudo apt-get update
sudo apt-get install sbt

After installing SBT, we’ll be running the following command to get a new play framework project with an SBT template.

sbt new playframework/play-scala-seed.g8

You’ll get an output similar to what’s given below:

This template generates a Play Scala projectname [play-scala-seed]: 
organization [com.example]:
play_version [2.8.13]:
scala_version [2.13.8]:

In this, you can change the name of the project, organization, version of your play application and scala or just press enter to stick with the original template.

After setting up your template, go to your play application directory using the name of your project.

cd play-scala-seed

Now, we’ll be running the template to see the base output without making any changes to our file.

sbt run

This will start your application

Now, go to your localhost to view your running application

http://localhost:9000

We’ve successfully set up our HTTP server in the Play Framework!

Now, we can make some small changes to our application.

If you open your play framework application, you’ll be able to see index.scala.html inside views which is inside app.

app -> views -> index.scala.html

Change the text given here and run your SBT if you stopped it or just hit refresh to view your changes.

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

You can also change your route to display whatever you want. For this, navigate to the following location

conf -> routes

Here, you can change the route as such

# An example controller showing a sample home pageGET     /hello_world                           controllers.HomeController.index()

You can also add more routes and use them for different purposes

Now, if you try http://localhost:9000/, it’ll throw the following error

This happens because we changed our base route to http://localhost:9000/hello_world . So, if we navigate to this URL, we’ll get our desired output.

Now that we’ve successfully set up our base application, we can add more actions or changes to it in order to use them efficiently.

Happy coding!

--

--