Building APIs with Play Framework
Introduction
The Play Framework is a powerful and flexible framework for building web applications in Scala and Java. It is particularly well-suited for building RESTful APIs due to its asynchronous nature and built-in support for JSON. In this tutorial, we will go through the steps required to build a simple REST API using the Play Framework and Scala.
Setting Up the Environment
Before we start building our API, we need to set up our development environment. Make sure you have the following installed:
- Java Development Kit (JDK) 8 or higher
- SBT (Scala Build Tool)
- Play Framework
Once you have these installed, create a new Play project by running the following command in your terminal:
This will create a new Play project with the necessary directory structure.
Creating the API Endpoints
Now that we have our project set up, we can start creating our API endpoints. In Play, we define routes in the conf/routes
file. Let’s create a simple API for managing users.
Open the conf/routes
file and add the following lines:
POST /users controllers.UserController.createUser()
GET /users/:id controllers.UserController.getUser(id: Long)
DELETE /users/:id controllers.UserController.deleteUser(id: Long)
This defines four endpoints: to get all users, create a new user, get a specific user by ID, and delete a user.
Implementing the Controller
Next, we need to implement the UserController
to handle these requests. Create a new Scala file in the app/controllers
directory named UserController.scala
and add the following code:
package controllers import javax.inject._ import play.api.mvc._ import play.api.libs.json._ import scala.collection.mutable.ListBuffer @Singleton class UserController @Inject()(val controllerComponents: ControllerComponents) extends BaseController { // In-memory user storage private val users = ListBuffer[User]() // User case class case class User(id: Long, name: String) implicit val userFormat: OFormat[User] = Json.format[User] def getAllUsers() = Action { implicit request: Request[AnyContent] => Ok(Json.toJson(users)) } def createUser() = Action(parse.json) { implicit request: Request[JsValue] => val user = request.body.as[User] users += user Created(Json.toJson(user)) } def getUser(id: Long) = Action { implicit request: Request[AnyContent] => users.find(_.id == id) match { case Some(user) => Ok(Json.toJson(user)) case None => NotFound } } def deleteUser(id: Long) = Action { implicit request: Request[AnyContent] => if (users.exists(_.id == id)) { users -= users.find(_.id == id).get NoContent } else { NotFound } } }
This controller uses an in-memory list to store users. We define the CRUD operations for the user resource using standard HTTP methods.
Testing the API
Now that we have our API implemented, we can test it using a tool like Postman or curl. Start your Play application by running:
Once the application is running, you can test the endpoints:
- Get All Users:
GET http://localhost:9000/users
- Create User:
POST http://localhost:9000/users
with JSON body{"id": 1, "name": "John Doe"}
- Get User:
GET http://localhost:9000/users/1
- Delete User:
DELETE http://localhost:9000/users/1
Conclusion
In this tutorial, we have built a simple REST API using the Play Framework and Scala. We covered setting up the environment, creating API endpoints, implementing the controller, and testing the API. The Play Framework provides a powerful and flexible way to build web applications and RESTful APIs efficiently.