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の行方
上記GreetingController
のgreeting()
では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!"}