0
2

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 Boot API設計の基本!パスパラとクエリパラメータの違いをサンプルで理解する

Posted at

パスパラメータとクエリパラメータの違いと使い分け

Spring BootでURLにパラメータを渡す方法は主に2つあります。

  1. パスパラメータ(@PathVariable
  2. クエリパラメータ(@RequestParam

1. パスパラメータ(@PathVariable)とは?

パスパラメータはURLのパス部分に値を直接埋め込みます。
例えば、/api/user/123 のように、123がユーザーIDを示す場合です。

  • 用途:リソース(ユーザーや商品など)の「識別子」を指定するときに使います。
  • 特徴:URLの構造が変わるためREST設計ではリソースの場所を表現するのに適しています

Spring Bootのコード例では、以下のように書きます。

@GetMapping("/api/user/{id}")
public Map<String, Object> getUserById(@PathVariable Long id) {
    // idを使って処理
}

2. クエリパラメータ(@RequestParam)とは?

クエリパラメータはURLの末尾に?で始まるパラメータを付けて送る方法です。
例えば、/api/user?id=123&name=山田太郎 のように複数の値を渡せます。

  • 用途:検索条件やフィルター、オプションの値など、リソースの識別子以外の値を渡すのに適しています
  • 特徴:パラメータはオプションとして指定でき、値がなくてもリクエスト可能です

Spring Bootのコード例では、以下のように書きます。

@GetMapping("/api/user")
public Map<String, Object> getUserByQuery(
    @RequestParam(name = "id", required = false) Long id,
    @RequestParam(name = "name", required = false) String name) {
    // idやnameを使って処理
}

required = falseを指定すると、そのパラメータは無くてもエラーになりません。

画面からの呼び出し例(jQuery)

  • パスパラメータ
$.ajax({
  url: '/api/user/123',
  type: 'GET',
  success: function(response) {
    console.log(response);
  }
});
  • クエリパラメータ
$.ajax({
  url: '/api/user',
  type: 'GET',
  data: { id: 123, name: '山田太郎' },
  success: function(response) {
    console.log(response);
  }
});

まとめ

種類 URL例 主な用途 特徴
パスパラメータ /api/user/123 リソースの識別子(IDなど) URLの一部として必須
クエリパラメータ /api/user?id=123&name=山田 検索条件やフィルターなど 任意のパラメータとして扱える
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?