3 years ago

REST API + many-to-many + idempotence

Posted 3 years ago by miso

Hi, I have DB entities User and Item and they have relation many-to-many (user has access to many items and one item is accesible by many users). There are attributes in the pivot table item_user:

  • item_id (composite 1. part)
  • user_id (composite 2. part)
  • created_at (just timestamp)
  • permissions (read/write/modify)

I have Laravel models User and Item which have many-to-many relationship via item_user. I do NOT have Access model for the pivot table (I want composite key only and Laravel does not support composite keys). I want to create symmetric REST API (no "Access" resource):

  • users/x/items/y
  • items/x/users/y (we can forget this for now)

The question is, which of PUT, POST to use when I want to link user with item? If I use

  • Route::resource('users.items', 'UserItemController');

then Laravel generates this:

  • POST | users/{users}/items
  • PUT|PATCH | users/{users}/items/{items}

Obviously, the first route does not make sense (I want to link existing user with existing item and new item should be created in route POST | items). But, If I use the second line, there is maybe the problem that it is not idempotent as created_at would be changed on each hit. (depends on implementation really, but look at this from REST perspective).

Should I use this instead (replace Route::resource with Route::post)?

  • POST | users/{users}/items/{items}

Is something wrong with this approach?

Thank you

Please sign in or create an account to participate in this conversation.