3

Suppose

GET /users/<id>

{
  user_id : "asdasdas-da-sd-asd-as-d",
  firs_name : "asdasd",
  ....
  department : [{
      id : "asdas-da-sdasd-asd",
      name : "asdasdasdasd",
      ...
      },]
}​

To add a new department for that user first create a department by:

POST /departments/ 

Then we use PATCH with department id

PATCH /users/<id>

{
   department : [
    "asdas-da-sdasd-asd", // #Existing department ids
    "new-one-id"     // # New ID
 ]
}

Is this method ok?

What is the best way to manage these in API side and considering the easiness in client side?

Or follow something like:

POST/PUT to  /user/<id>/departments/[<id>]

to add/update the department

or

DELETE to /user/<id>/departments/<id>

to remove that dept from list

  • we do not use DELETE, but only make the field active using PATCH or PUT
7

To list the user departments

Use GET /users/<id>/departments, instead of returning this info in the users resource.

Doing so allow the below topics to work well in the most RESTful manner - the user-departments relation will always be available under /users/<id>/departments, instead of sometimes available under /users/<id>.

To assign an department to a user

The best design, IMO, is a PUT /users/<id>/departments/<id>:

  • The PUT method is idempotent - if you do it more than once, the result will always be the same;
  • By declaring in the URL the department you want to add, the request body can be empty - unless you need to parameterize this relation somehow;
  • Be sure to always return an 200 OK (instead of a 201 Created the first time), so the request is always the same

To remove an department from a user

Keep doing DELETE /users/<id>/departments/<id>.

It doesn't matter what your server is doing (deleting or flagging the user-departments relation).
The proposal of the DELETE method is to make something unavailable from now on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.