Search code examples
restgetput

REST url design


Let's you have an url like this:

POST /departments, which creates a new department
and POST /employees, which creates a new employ.

Both url returns a location header for the newly created resource, etc.

Assume that an employee can belong to multiple departments.

How would you structure the corresponding URL and most important would you use POST or PUT to perform this operation? E.g.: to add Bill to the books department, would you use:

POST /departments/Books/employees/Bill

Or:

PUT /departments/Books
{
  "employee" : "Bill"
}

The former looks to me more semantically correct since anyway in the POST body i have more data that characterizes this new relationship. Moreover

GET /employee/Bill returns a body that is different from the one returned by:
GET /departments/Books/employees/Bill

So to me adding the relationship is like creating a new resources. However I do not like the fact that in
POST /departments/Books/employees/Bill I'm explicitly naming the new resource in the URL.


Solution

  • Assuming you know the name of the employee before hand it seems the easiest way of doing this is to use PUT

    PUT /departments/books/employees/bill
    

    If resource "Bill" is completely new then return a 201. If "Bill" already exists then return 200.

    GET /departments/books/employees/bill
    

    and

    GET /dapartments/giftcards/employees/bill
    

    and

    GET /employees/bill
    

    should return the same data. I'm not sure why it wouldn't if "Bill" is the same resource in both cases.