LoginSignup
4

More than 5 years have passed since last update.

api blueprintでData Structuresを利用する際の注意点

Posted at

概要

restfulなapiを設計すっぞ。となっても、「けど同じ戻り値を何回も書きたくない!めんどくさい!」ってなりますよね。

そんなときに、Data Structuresというデータ型定義の方法が使えると知ったのですが、一部ハマったので書き留めておきます。

Data Structuresについては下記を参考にさせてもらいました。感謝!

api blueprint でData Structuresを用いてIFを定義する
https://qiita.com/haseshin/items/1394b0c70e25c9f51762

Data Structuresを利用してみる

Data Structuresを利用しない場合、/hoges のGETはリストで、hoges/{id} のGETはオブジェクトで返すわけですが、オブジェクトの内容は同じになります。
今回はサンプルなので、idname しかないですが、実際はもっと項目は多いわけで。。。
あとは分かりますよね。。。

# hogeリソース

## hoge情報 [/hoges]

### hoge情報を取得する [GET /hoges]

+ Response 200 (application/json)

    + Attributes
        + items (array, fixed-type)
            + (object)
                + id : 1 (number) - ID
                + name : hoge (string) - 名前

## hoge情報 [/hoges/{id}]

+ Parameters

    + id : 1 (number) - ID


### hoge情報を取得する [GET]

+ Response 200 (application/json)

    + Attributes
        + id : 1 (number) - ID
        + name : hoge (string) - 名前

で、Data Structuresを利用して戻り値をデータ型定義するとスッキリする!
というわけで、先の記事が参考になります。

api blueprint でData Structuresを用いてIFを定義する
https://qiita.com/haseshin/items/1394b0c70e25c9f51762

記事に習って、まずはData Structuresを定義します。

# Data Structures

## Hoge (object)
+ id : 1 (number) - ID
+ age : hoge  (string) - 名前

hoges/{id} の戻り値に指定してみます。

## hoge情報 [/hoges/{id}]

+ Parameters

    + id : 1 (number) - ID


### hoge情報を取得する [GET]

+ Response 200 (application/json)

    + Attributes
        + hoge (Hoge)

これで、戻り値はData Structuresを参照することになるので、楽で良いね!

それでは、良きapi blueprintを利用した設計ライフを^^



となれば良かったのですが、実際にjsonの戻り値を見てみます。

{
  "hoge": {
    "id": 1,
    "age": "hoge"
  }
}

はい。
おわかりいただけるでしょうか。。。

"hoge": { ... } はいらないんやー。となります。

どうすればよいのか小一時間悩んだ挙げ句、下記のようにすれば良いことがわかりました。

## hoge情報 [/hoges/{id}]

+ Parameters

    + id : 1 (number) - ID


### hoge情報を取得する [GET]

+ Response 200 (application/json)

    + Attributes (Hoge)

結果を見てみます。

{
  "id": 1,
  "age": "hoge"
}

はい。
期待していた戻り値となりました。

以下がData Structuresを適用したバージョンとなります。

# Data Structures

## Hoge (object)
+ id : 1 (number) - ID
+ age : hoge  (string) - 名前


# hogeリソース

## hoge情報 [/hoges]

### hoge情報を取得する [GET /hoges]

+ Response 200 (application/json)

    + Attributes
        + items (array[Hoge], fixed-type)


## hoge情報 [/hoges/{id}]

+ Parameters

    + id : 1 (number) - ID

### hoge情報を取得する [GET]

+ Response 200 (application/json)

    + Attributes (Hoge)

それでは、良きapi blueprintを利用した設計ライフを^^

PS) hogeに複数形はあるのでしょうか・・・知りたい

参考

api blueprint でData Structuresを用いてIFを定義する
https://qiita.com/haseshin/items/1394b0c70e25c9f51762

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
4