mmts1007’s diary

プログラミング関連の技術系ブログです。

Java Spring Boot その4

今回は Spring Boot を使って REST API を作ろうと思います。

DB を使わず、モックを使用します。
次回以降、モックの実装を DB を使った実装に修正しようと思います。

一覧取得

まずは一覧を取得するソースのみ

package hello;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api/tasks")
@EnableAutoConfiguration
public class RestSampleController {

    static class Task {
        Task(String title, String context) {
            this.title = title;
            this.context = context;
        }

        public String title;
        public String context;
    }

    @RequestMapping(method = RequestMethod.GET)
    List<Task> getTasks() {
        List<Task> tasks = new ArrayList<>();
        tasks.add(new Task("sample1", "sample1"));
        tasks.add(new Task("sample2", "sample2"));
        tasks.add(new Task("sample3", "sample3"));

        return tasks;
    }

    public static void main(String[] args) {
        SpringApplication.run(RestSampleController.class, args);
    }
}

http://localhost:8080/api/tasks にアクセスすると

[
    {
        "title": "sample1",
        "context": "sample1"
    },
    {
        "title": "sample2",
        "context": "sample2"
    },
    {
        "title": "sample3",
        "context": "sample3"
    }
]

上記内容が返ってくると思います。
※上記 JSON は整形しています

解説

@RequestMapping("api/tasks") をコントローラクラスに付与することで、このクラスが "api/tasks" とマッピングされます。

@RequestMapping(method = RequestMethod.GET) を getTasks メソッドに付与することで GET "api/tasks" が getTasks メソッドマッピングされます。

同様に POST, PUT, DELETE をマッピングするメソッドを作成すれば、REST API の作成は完了です。
今回はここまで。