0Pricing
Scala for Backend Engineering & Functional Programming · Lección

Construcción de API RESTful con Play

Diseñe e implemente endpoints RESTful, gestione solicitudes y administre datos JSON con los controladores de Play.

Construcción de API RESTful con Play es una lección gratuita de Scala for Backend Engineering & Functional Programming en CoddyKit. Esta es la lección 2 de 3. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Scala for Backend Engineering & Functional Programming, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Scala for Backend Engineering & Functional Programming incluye 3 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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!

Preguntas frecuentes

¿La lección «Construcción de API RESTful con Play» es gratis?

Sí — el texto completo de «Construcción de API RESTful con Play» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Scala for Backend Engineering & Functional Programming, actualiza a CoddyKit PRO. El curso de Scala for Backend Engineering & Functional Programming incluye 3 lecciones en total.

¿Qué aprenderé en «Construcción de API RESTful con Play»?

Diseñe e implemente endpoints RESTful, gestione solicitudes y administre datos JSON con los controladores de Play. Practicas Scala for Backend Engineering & Functional Programming con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Scala for Backend Engineering & Functional Programming?

No se requiere experiencia previa. Scala for Backend Engineering & Functional Programming en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 3.

¿Cuánto tiempo toma la lección «Construcción de API RESTful con Play»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Scala for Backend Engineering & Functional Programming?

Sí. Cada lección de Scala for Backend Engineering & Functional Programming incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Fundamentos de Play Framework
  2. Construcción de API RESTful con Play
  3. Integración de bases de datos con Slick/Doobie
← Volver a Scala for Backend Engineering & Functional Programming