Building RESTful APIs with Play
Design and implement RESTful endpoints, handle requests, and manage JSON data with Play controllers.
Building RESTful APIs with Play is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Intro to Play REST APIs
Welcome! In this lesson, we'll dive into building RESTful APIs using the Scala Play Framework. REST (Representational State Transfer) is a widely used architectural style for designing networked applications.
A RESTful API allows different software systems to communicate with each other over the internet, typically using standard HTTP methods like GET, POST, PUT, and DELETE to perform operations on resources.
Play Controllers & Actions
In Play, incoming HTTP requests are handled by controllers. A controller is a Scala object or class that contains action methods.
Each action method is responsible for processing a specific type of request (e.g., fetching data, creating a new item) and returning an HTTP response.
Defining Routes in Play
Play uses a conf/routes file to map incoming HTTP requests to specific controller action methods. This is where you define your API's endpoints.
The basic syntax for a route entry is: HTTP_METHOD /path controllers.ControllerName.actionMethod(parameters).
Implementing a GET Endpoint
Let's create a simple GET endpoint that returns a greeting. In a real Play app, this would be inside a controller. Here, we simulate the logic in a main method.
Try running this example:
object GreetingController {
// This method simulates a Play controller action
def sayHello(): String = {
"Hello from your Play API!"
}
def main(args: Array[String]): Unit = {
// Simulate receiving a request and calling the action
val apiResponse = sayHello()
println(s"Simulated API Response: $apiResponse")
}
}Extracting Path Parameters
Often, you need to extract dynamic values from the URL path, like an item ID. These are called path parameters.
In the routes file, you define them with a colon (:). In your controller action, you declare them as method parameters.
object UserController {
// This action takes an 'id' as a path parameter
def getUser(id: Int): String = {
s"Fetching user details for ID: $id"
}
def main(args: Array[String]): Unit = {
// Simulate a request to /users/123
val userIdFromRequest = 123
val apiResponse = getUser(userIdFromRequest)
println(s"Simulated API Response: $apiResponse")
}
}Request Bodies & JSON
For creating or updating resources, clients send data in the request body. For RESTful APIs, this data is almost always in JSON (JavaScript Object Notation) format.
Play provides excellent support for parsing JSON request bodies and converting them into Scala case classes.
Building a POST Endpoint
Let's simulate a POST endpoint that receives a JSON body. In a real Play app, you'd use Play's JSON library to parse the request. For this runnable example, we'll check for simple string content.
Try running this example:
object ItemController {
// Simulate processing a JSON request body
def createItem(jsonBody: String): String = {
// In a real Play app: Json.parse(jsonBody).as[ItemCaseClass]
if (jsonBody.contains("name") && jsonBody.contains("price")) {
s"Item successfully created! Data: $jsonBody"
} else {
"Error: Invalid JSON format. 'name' and 'price' expected."
}
}
def main(args: Array[String]): Unit = {
// Simulate a POST request with a JSON body
val validJson = """{"name": "Smartphone", "price": 799.99}"""
println(s"Valid JSON Response: ${createItem(validJson)}")
val invalidJson = """{"product": "Tablet"}"""
println(s"Invalid JSON Response: ${createItem(invalidJson)}")
}
}Handling PUT and DELETE
Besides GET and POST, RESTful APIs commonly use:
- PUT: To update an existing resource. Usually requires a path parameter (ID) and a request body (updated data).
- DELETE: To remove a resource. Typically only requires a path parameter (ID).
The patterns for defining routes and accessing parameters/bodies for PUT and DELETE are similar to POST and GET.
Returning JSON Responses
After processing a request, your API usually needs to send back a response, often in JSON format. Play makes it easy to construct JSON objects and send them back.
In a controller, you'd typically use Ok(Json.toJson(yourCaseClass)). Here, we simulate creating a JSON string.
object ResponseGenerator {
// Simulate a case class for the response data
case class ApiResponse(status: String, message: String)
// Simulate converting the case class to a JSON string
def buildJsonResponse(response: ApiResponse): String = {
s"""{"status": "${response.status}", "message": "${response.message}"}"""
}
def main(args: Array[String]): Unit = {
val successResponse = ApiResponse("success", "Data retrieved successfully")
println(s"Simulated JSON Output:\n${buildJsonResponse(successResponse)}")
val errorResponse = ApiResponse("error", "Item not found")
println(s"Simulated JSON Output:\n${buildJsonResponse(errorResponse)}")
}
}Route Matching Quiz
Which Play route definition would correctly match a request to GET /api/products/123 and pass 123 as an Int to the controller action?
Recap & Next Steps
Great job! You've learned the fundamentals of building RESTful APIs with Play Framework:
- Understanding RESTful principles and HTTP methods.
- How Play controllers and actions process requests.
- Defining API routes to map URLs to controller actions.
- Extracting path parameters from URLs.
- Handling JSON request bodies for POST/PUT.
- Constructing and returning JSON responses.
Next, you might explore integrating databases with your Play application!
Frequently asked questions
Is the “Building RESTful APIs with Play” lesson free?
Yes — the full text of “Building RESTful APIs with Play” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.
What will I learn in “Building RESTful APIs with Play”?
Design and implement RESTful endpoints, handle requests, and manage JSON data with Play controllers. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Scala for Backend Engineering & Functional Programming?
No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Building RESTful APIs with Play” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?
Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Play Framework Fundamentals
- Building RESTful APIs with Play
- Database Integration with Slick/Doobie