0Pricing
Scala for Backend Engineering & Functional Programming · レッスン

PlayでRESTful APIを構築する

Playのコントローラーを使ってRESTfulエンドポイントを設計・実装し、リクエストを処理してJSONデータを管理します。

「PlayでRESTful APIを構築する」はCoddyKit上の無料Scala for Backend Engineering & Functional Programmingレッスンです。 これはレッスン2/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはScala for Backend Engineering & Functional Programming学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Scala for Backend Engineering & Functional Programmingコースには全3レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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!

よくある質問

「PlayでRESTful APIを構築する」レッスンは無料ですか?

はい。「PlayでRESTful APIを構築する」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Scala for Backend Engineering & Functional Programmingコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Scala for Backend Engineering & Functional Programmingコースには全3レッスンが含まれています。

「PlayでRESTful APIを構築する」で何を学びますか?

Playのコントローラーを使ってRESTfulエンドポイントを設計・実装し、リクエストを処理してJSONデータを管理します。 ブラウザで直接実行するハンズオンコードでScala for Backend Engineering & Functional Programmingを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Scala for Backend Engineering & Functional Programmingを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのScala for Backend Engineering & Functional Programmingは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/3です。

「PlayでRESTful APIを構築する」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このScala for Backend Engineering & Functional Programmingレッスンでコードを書いて実行できますか?

はい。すべてのScala for Backend Engineering & Functional Programmingレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. Play Frameworkの基礎
  2. PlayでRESTful APIを構築する
  3. Slick/Doobieによるデータベース連携
← Scala for Backend Engineering & Functional Programmingに戻る