Reputation: 1701
My questions are based on this article: should-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}
The response data of a single user looks like this:
Id: 1
Firstname: Alice
Lastname: Henderson
Email: [email protected]
Roles: api/users/1/roles
To get the roles of this user the application needs to call the returned url api/users/1/roles
For displaying 1 user this approach seems to be ok. 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
How can this design be improved for retrieving multiple users and resolving their role relationships?
Upvotes: 1
Views: 184
Reputation: 13672
You can design your API to accept one or more query parameters which specify the detail level you desire. For instance:
GET /api/users/1?expand=role(self, id, name)
{
"id": 1
"firstName": "Alice"
"lastName": "Henderson"
"email": "[email protected]"
"roles": [
{
"self": "api/roles/4"
"id": 4
"name": "Administrator"
},
{
"self": "api/roles/7"
"id": 7
"name": "Uberuser"
}
]
}
Upvotes: 1