【问题标题】:Sub-collections in REST apiREST api 中的子集合
【发布时间】:2018-08-23 03:52:10
【问题描述】:

一个资源可以有多少个子集合?

想象一下我们有这个模型: 帐户 -> 帖子 -> cmets

帐户-帖子对的一切都很清楚。 /accounts/{account_id}/posts/{post_id}

但是 cmets 呢?指向单个评论的正确方法是什么?

/posts/{post_id}/cmets/{comment_id}

/accounts/{account_id}/posts/{post_id}/cmets/{comment_id}

或(直接指向)

cmets/{comment_id}

【问题讨论】:

    标签: rest api collections resources


    【解决方案1】:

    一般的经验法则是只深入一层子资源。一个帐户可能有很多像您显示的帖子,一个帖子可能有很多 cmets,但由于帖子 ID 是唯一的,因此在尝试获取帖子的 cmets 时,包括帐户 ID 有点多余。

    /accounts/:account_id/posts

    /posts/:post_id/cmets

    Ruby On Rails 也在他们的文档中列出了这一点(只是为了引用)。 https://guides.rubyonrails.org/routing.html#limits-to-nesting

    此外,如果您已经拥有资源的 id,则不需要嵌套它。由于缺少完成工作的路线是首选。

    /cmets/:id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多