简体   繁体   English

在这种具体情况下,我应该如何设计我的RESTful API?

[英]How should I design my RESTful API in this concrete case?

I am building an API with Loopback.io, and I have been thinking about how should I design some of the endpoints. 我正在使用Loopback.io构建API,并且一直在思考如何设计一些端点。 To get in context: 要获得上下文:

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.

Now I have (A) : 现在我有(A)

  1. /People /人
  2. /People/{id}/Groups /人/(编号)/组
  3. /Groups /组
  4. /Groups/{id}/Sessions /组/ {ID} /会话

which is the API generated by Loopback. 这是Loopback生成的API。 2 and 3 are "repeated" endpoints, however 2 creates a Member instance and 3 does not. 2和3是“重复的”端点,但是2创建一个Member实例,而3没有。

Option B : 选项B

  1. /People /人
  2. /People/{id}/Groups /人/(编号)/组
  3. /People/{id}/Groups/{groupId}/Sessions /人/(编号)/组/ {}的groupId /会话

Option C : 选项C

  1. /People /人
  2. /Groups /组
  3. /Groups/{id}/Sessions /组/ {ID} /会话

I would like to know which is the best approach and if the A solution would be good enough. 我想知道哪种方法最好,以及A解决方案是否足够好。 Thank you very much. 非常感谢你。

Go with something closest to Option C: 选择最接近选项C的内容:

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

Your resources then look something like this: 您的资源如下所示:

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"
}

My advice is always to avoid nesting URIs unless there is a very good argument for doing so. 我的建议始终是避免嵌套URI,除非有很好的论据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM