Search code examples
restapi-designendpoint

REST endpoint to replace a member of a group


There are multiple collections and each can be identified by a unique ID. Withing each collection are multiple people and each can be identified by their employee ID. Obviously, a single person cannot be in the same collection twice.

I will need to replace a given person with a new person in a given collection.

Should this be done using two endpoints:

DELETE /collections/123/employees/321
POST   /collections/123 {"employeeId": 222}

Or can it be done with one:

PUT /collections/123/employees/321 {"employeeId": 222}

Solution

  • A PUT should be idempotent:

    An HTTP method is idempotent if an identical request can be made once or several times in a row with the same effect while leaving the server in the same state. In other words, an idempotent method should not have any side-effects (except for keeping statistics). Implemented correctly, the GET, HEAD, PUT, and DELETE method are idempotent, but not the POST method.

    What should happen in the back-end if you call:

    PUT /collections/123/employees/321 {"employeeId": 222}
    PUT /collections/123/employees/321 {"employeeId": 222}
    PUT /collections/123/employees/321 {"employeeId": 222}
    PUT /collections/123/employees/321 {"employeeId": 222}
    

    If the 321 record no longer exists, how should it be handled? If the new employeeId already exists, how should it be handled?

    Logically, to me, it would make more sense to keep them as two separate calls (removing the old member, and adding a new member). While you could handle this in a PUT request while keeping the request idempotent, it isn't very clear to a potential user what the intended functionality of this call is.