我应该如何在这个具体案例中设计我的RESTful API?

时间:2015-04-07 16:31:49

标签: api rest loopbackjs endpoints

我正在使用Loopback.io构建API,我一直在考虑如何设计一些端点。 了解情况:

a Person hasMany Groups,
a Group hasMany People (and one of them is the admin),
a Member is the "Through" model for Person and Group,
a Group hasMany Sessions.

现在我有(A)

  1. /人
  2. / People / {id} / Groups
  3. / Groups
  4. /组/ {ID} /会话
  5. 这是Loopback生成的API。 2和3是“重复”端点,但是2创建了一个Member实例,而3则没有。

    选项B

    1. /人
    2. / People / {id} / Groups
    3. /人/ {ID} /组/ {的groupId} /会话
    4. 选项C

      1. /人
      2. /组
      3. /组/ {ID} /会话
      4. 我想知道哪种方法最好, A 解决方案是否足够好。 非常感谢你。

1 个答案:

答案 0 :(得分:1)

选择最接近选项C的东西:

/people
/people/{person_id}
/groups
/groups/{group_id}
/sessions
/sessions/{session_id}

您的资源看起来像这样:

GET /people/1
{
  "person_id": 1,
  "groups": [
    "/groups/5",
    "/groups/7"
  ]
}

GET /groups/5          (Option 1 - if every group has exactly one admin)
{
  "group_id": 5,
  "admin": "/people/1",
  "members": [
    "/people/1",
    "/people/4",
    "/people/5"
  ],
  "sessions": [
    "/sessions/2",
    "/sessions/3"
  ]
}

GET /groups/5          (Option 2 - if groups can have any number of admins)
{
  "group_id": 5,
  "members": [
    {
      "person": "/people/1",
      "is_admin": true,
    },
    {
      "person": "/people/4",
      "is_admin": false
    },
    {
      "person": "/people/5",
      "is_admin": false
    }
  ],
  "sessions": [
    "/sessions/2",
    "/sessions/3"
  ]
}

GET /sessions/3
{
  "session_id": 3,
  "group": "/groups/5"
}

我的建议总是避免嵌套URI,除非有一个很好的论据。