【问题标题】:What is the correct URI design for a REST service with associated resources具有关联资源的 REST 服务的正确 URI 设计是什么
【发布时间】:2013-04-25 07:51:13
【问题描述】:

大家好,

我是 REST 和 Web API 的新手。我对如何为我的资源设计 URI 感到有些困惑。

鉴于我有一个包含以下资源的域:博客、帖子和用户。

Blog (1) ------ (0..*) Post (0..*) ------ (1) User

一个博客可以有很多帖子,每个帖子都与一个博客相关联。一个用户可以有很多帖子,每个帖子都与一个用户相关联。

对于博客和用户资源,URI 如下所示:

GET /blogs - get list of all blogs
GET /blogs/{id} - get blog by id
POST /blogs - create new blog
PUT /blogs/{id} - update blog
DELETE /blogs/{id} - delete blog

GET /users- get list of all users
GET /users/{id} - get user by id
POST /users - create new user
PUT /users/{id} - update user
DELETE /users/{id} - delete user

但是 Posts 资源呢?如何处理关联?我正在考虑以下替代方案 - 哪些是正确的,为什么?

-- 获取博客的所有帖子

1. GET /blogs/{id}/posts
or
2. GET /posts?blogid={id}

-- 在博客中创建新帖子

3. POST /blogs/{id}/posts
or
4. POST /posts (here I would then in the payload send the IDs of the resources this post is associated with. BlogId and UserId)

-- 按博客和用户获取所有帖子

5. GET /blogs/{id}/posts?userid={id}
or
6. GET /posts?blogid={id}&userid={id}

如果有人能在这里指出正确的方向,我将不胜感激。

【问题讨论】:

    标签: web-services rest asp.net-web-api


    【解决方案1】:

    由于帖子始终与博客和用户 ID 相关联,因此我会选择选项 1、3 和 5:

    GET /blogs/{id}/posts
    POST /blogs/{id}/posts
    GET /blogs/{id}/posts?userid={id}
    

    【讨论】:

      【解决方案2】:

      您应该问自己的第一个问题是,您的 API 真正 RESTful 对您来说有多重要?它实际上比看起来要复杂得多。

      1. 您的 API 是否将仅由您自己的软件\组织使用?

      2. 您的 API 会附有文档吗?

      如果上面 1 或 2 的答案是正确的,那么真正 RESTful 的价值是值得怀疑的...... REST 要么全有,要么全无,所以要么全力以赴,要么不用担心。

      要使 API 成为真正的 REST API,它必须可以从单个入口点发现(参见此处:http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven)。每个调用都应返回有关可以对该资源进行的其他相关调用的信息。通常通过某种链接,这是一种可能的结构:

      {
          "Id" : 1,
          "Identifier" : "123's First Blog",
          "links" : [
              {
                  "rel": "http://myapi/res/posts",
                  "href": "http://myapi/blog/1/posts"
              },
              {
                  "rel": "http://myapi/res/users",
                  "href": "http://myapi/user/123"
              }
          ]
      }
      

      rel 是指向资源摘要\定义的链接,href 应指向 api 本身。

      无论如何,所有这一切的重点是,如果您确实想成为真正的 RESTful,那么让资源和 uris 之间的链接决定设计。想一想您将如何从一个单一的起点发现每个调用的细节,并且结构应该像通过 TDD 的软件设计一样显示出来。

      如果您不需要 RESTful,那么事情就会变得简单得多。只需以最自然的方式为您、您的架构和您的开发人员设计您的 API。如果您正确地记录事物,那么这将导致更高效的 API 和更快的开发速度。

      马里奥对这个问题的回答是合理的,我也更喜欢这些选项。我只是觉得你应该知道伴随着这样一个决定的整个故事。

      如果这没有意义,或者您想了解更多信息,请发表评论,我会尽力提供帮助 :)

      【讨论】:

      猜你喜欢
      • 2012-01-07
      • 1970-01-01
      • 2017-12-22
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      相关资源
      最近更新 更多