简体   繁体   English

RESTful设计:解决关系

[英]RESTful design: resolving relationships

My questions are based on this article: should-restful-apis-include-relationships 我的问题是基于这篇文章的: 应该-restful-apis-include-relationships

Let's say I have the following resources: users and roles 假设我有以下资源:用户和角色

A single user can be retrieved by api/users/{userId} and a single role by api/roles/{roleId} 可以通过api / users / {userId}检索单个用户,并且可以通过api / roles / {roleId}检索单个角色

The response data of a single user looks like this: 单个用户的响应数据如下所示:

Id: 1
Firstname: Alice
Lastname: Henderson
Email: alice@henderson.com
Roles: api/users/1/roles

To get the roles of this user the application needs to call the returned url api/users/1/roles 要获得此用户的角色,应用程序需要调用返回的url api / users / 1 / roles

For displaying 1 user this approach seems to be ok. 对于显示1位用户,此方法似乎可以。 But if I want to display all users with their corresponding roles the application needs 1 call to api/users and x calls to api/users/x/roles 但是,如果我想显示所有具有相应角色的用户,则应用程序需要1次调用api / users和x次调用api / users / x / roles

How can this design be improved for retrieving multiple users and resolving their role relationships? 如何改进此设计以检索多个用户并解决他们的角色关系?

You can design your API to accept one or more query parameters which specify the detail level you desire. 您可以将API设计为接受一个或多个查询参数,这些参数指定所需的详细程度。 For instance: 例如:

GET /api/users/1?expand=role(self, id, name)

{
    "id": 1
    "firstName": "Alice"
    "lastName": "Henderson"
    "email": "alice@henderson.com"
    "roles": [
        {
            "self": "api/roles/4"
            "id": 4
            "name": "Administrator"
        },
        {
            "self": "api/roles/7"
            "id": 7
            "name": "Uberuser"
        }
    ]
}

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

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