0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Spring】REST APIの作成①GET

Last updated at Posted at 2025-05-04

■ リクエストの送信

GETリクエストで、データを取得するリクエストを送る。

rest-get.png
↑Acceptヘッダで 取得するデータの形式をJSON形式に指定している。
デフォルト設定は「* / *」(=なんでも受け付ける)であり、SpringBootは自動で適切な形式(ほぼJSON)を選んで返すので、特に何も指定しなくてもJSONで返ってくる。

const id = 1
const res = await fetch(`/api/words/${id}`, {
    method: "GET", //GETの場合は省略可
    headers: {  //省略可
        "Accept": "application/json"
    }
});		

■ コントローラでハンドリング

@Controller
public class WordApiController {

    @GetMapping("/api/words/{id}")
    @ResponseBody
    public WordDto getWordsById(@PathVariable("id") Integer id){
        return wordService.findById(id);
    }
}

メソッドに@ResponseBody を付けることで、戻り値の WordDto オブジェクトが JSON形式に変換されてレスポンスされるようになる(Springの HTTPMessageConverter が自動で処理)

毎回メソッドごとに @ResponseBody を書くのは面倒なので、クラスに @RestController を付けることで次のように書ける。

@RestController
public class WordApiController {

    @GetMapping("/api/words/{id}")
    public WordDto getWordsById(@PathVariable("id") Integer id){
        return wordService.findById(id);
    }
}

■ HTTPMessageConverterがJavaオブジェクトをJSONに変換

rest-get-res.png

■ クライアント側(JS)でJSONを取得する

if(res.ok){
const word = await res.json();
//wordのプロパティから値を参照できる
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?