SpringBootでシンプルなGET APIを作った

外部システムとの連携のための知識があまり無いと思っていたので、勉強し直すことにしました。

最初は、GETリクエストに対して簡単なレスポンスを返すアプリケーションを作ります。

ソースコード全体は↓にあります。

https://github.com/bond-kaneko/SpringBootRestApp

できること

GETリクエストに対して、下記のようなレスポンスを返します。

{"id":1,"content":"Hello, World!"}%         

Controllerアノテーション

REST API用のControllerを作成する場合、@RestControllerアノテーションをControllerクラスに付けます。 こうすると、@GetMapping@PostMappingなどが使用できるようになります。

@RestController
public class GreetingController {
...

リクエスマッピング

各エンドポイントとメソッドを紐付けるには、@RequestMappingアノテーションを使います。

@RequestMapping(method=RequestMethod.GET, value="/")とすると、ルートパスに対するGETリクエストとアノテーションをつけたメソッドが紐付けられます。 @GetMapping@PostMapping@RequestMapping(method=RequestMethod.GET)と同じ働きをします。

@GetMapping("/greeting")
    public Greeting greeting() {
    ...

クエリパラメータ

メソッドの引数に@RequestParamアノテーションを付ければ、クエリパラメータを受け取れるようになります。

public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
...
    

valueがパラメータkeyで、keyが存在しなかった場合のデフォルト値をdefaultValueで指定できます。

Controllerクラス全体

package com.example.SpringBootRestApp.restservice;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
public class GreetingController {
    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

returnされたGreetingの行方

上記GreetingControllergreeting()ではGreetingインスタンスを返しています。

本来返すべきなのはJSONであって、Greetingインスタンスではないのですが、インスタンスJsonに変換する機能をSpringが提供してくれているので、明示的に変換する必要はありません。

動作検証

クエリパラメータ付きのリクエストに対応できます。

% curl http://localhost:8080/greeting?name=Test
{"id":2,"content":"Hello, Test!"

クエリパラメータが存在しない場合は、デフォルト値を返します。

% curl http://localhost:8080/greeting
{"id":1,"content":"Hello, World!"}