Search code examples
restweb-servicesapi-design

How to design a REST API that doesn't require a client to make many requests to get the data it needs?


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?


Solution

  • 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.