Nested REST resources

71 Views Asked by At

I have Department Resource and each department can have multiple classes. So, for example:

Dept # 100 can have class = 1, 2, 3, 4, 5 Dept # 200 can have class = 2, 3, 9, 12

I want to get classes by specific class id, multiple class id, specific department id, multiple department ids. Here is what I think about making the URL:

   /depts    -->         displays all departments

   /depts?_id = 100 & _id = 200       -->      displays departments with id 100 and 200

   /depts/100                --> display department with id = 100

   /classes   --> displays all classes

   /classes?_id = 1 & _id = 2 -->  displays classes with id = 1 and id = 2

   /classes/1 -->display class with id = 1

Now,

  1. How would I display all classes in a specific department ( ex: all classes in department 100).

would this work?

  /classes?dept=/depts/{100}

or

  /depts/100/classes
  1. How would I display all classes in multiple departments ( ex: all classes in department 100 and department 200).

would this work?

  /classes?dept=/depts/{100}&dept=/depts/{200}
1

There are 1 best solutions below

5
On

You can follow the following rules:

  1. GET /depts/ returns departments
  2. GET/depts/{id}/ returns department with given ID
  3. GET /depts/{id}/classes/ returns classes for department with given ID
  4. GET/classes/ returns all classes
  5. GET /clasess/{id}/ returns a class for given ID

The tricky part is to get classes that belong to multiple depts. It can be done with

  1. GET /classes/?deptID=1&deptID=2 - a simple GET request with filtering via query params
  2. POST /classes/filter - POST request with all the necessary params sent in body.

Both 1. and 2. are equally good for such filtering.