Reputation: 15588
Suppose you are creating a service with the often-used example of department
and employee
resources. The endpoints for retrieving these might look like
/api/departments
/api/employees?department=21
Now suppose an iPhone client app wanted to use this service to show a big table of employees and the departments they belong to. It seems like a developer would first need to make a request to get all the departments, then for each department found, make a request to get the employees for that department. Finally on the client-side, the data would need to be stitched together and the joined result presented to the user.
Is there a different REST principle to follow here that would lead to fewer requests needing to be made? Should one create an /api/employessByDepartment
endpoint that returnes everything in one shot?
Upvotes: 0
Views: 76
Reputation: 7744
There is a solution for that already on the market, it's called the Web. :) If you want to "show a big table of employees and departments they belong to", you could just emit an HTML page with a table.
If you don't like HTML, you can have an alternative representation of the exact same resource in JSON or XML or CSV, or whatever you want, just implement serving the proper media-type
on the server, and you're done.
As you said, just create the resource for exactly what you need. Don't complicate it.
Upvotes: 1
Reputation: 4620
REST is really just how the client interacts with the domain of the system. A very simple domain might have the concept of employee and department with no architectural links between them other than the database schema. e.g. An employee can be in one department and one department can have many employees.
If the client needs them both together, that might indicate there's an area of the domain that is interacted with frequently. Employees and their departments or vice versa. Why would the client need to ask that? Why would it need all that data?
There's a symbiotic relationship between the domain and the client. The domain supports what the client requires in order to let the client work with the end user. So perhaps the domain might need to support a higher level concept that supports what the client is trying to do with the user of the app.
A REST approach to the issue might be:
/api/department/employees
/api/employees/department
a domain oriented approach to the issue might be:
/api/company/structure
which returns all employees and their departments.
Upvotes: 1
Reputation: 1573
How about reusing the same /api/employees
and adding a groupBy
parameter?
/api/employees?groupBy=department
Upvotes: 1