0Pricing
Scala for Backend Engineering & Functional Programming · Aula

Construindo APIs RESTful com Play

Projete e implemente endpoints RESTful, trate requisições e gerencie dados JSON com controllers do Play.

Construindo APIs RESTful com Play é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 2 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Scala for Backend Engineering & Functional Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Scala for Backend Engineering & Functional Programming inclui 3 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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!

Perguntas Frequentes

A aula “Construindo APIs RESTful com Play” é grátis?

Sim — o texto completo de “Construindo APIs RESTful com Play” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Scala for Backend Engineering & Functional Programming, atualize para CoddyKit PRO. O curso de Scala for Backend Engineering & Functional Programming inclui 3 aulas no total.

O que vou aprender em “Construindo APIs RESTful com Play”?

Projete e implemente endpoints RESTful, trate requisições e gerencie dados JSON com controllers do Play. Você pratica Scala for Backend Engineering & Functional Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Scala for Backend Engineering & Functional Programming?

Nenhuma experiência prévia é necessária. Scala for Backend Engineering & Functional Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 3.

Quanto tempo leva a aula “Construindo APIs RESTful com Play”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Scala for Backend Engineering & Functional Programming?

Sim. Cada aula de Scala for Backend Engineering & Functional Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Fundamentos do Play Framework
  2. Construindo APIs RESTful com Play
  3. Integração com bancos de dados usando Slick/Doobie
← Voltar para Scala for Backend Engineering & Functional Programming