Reputation: 411
I have 4 Apis that I expose, and I don't know what method should I use for them (POST/PUT/DELETE).
The DB object (let's call it User) contains
{"id", "foreignId1", "foreignId2"}
I have 4 methods -
assignForegin1
unassignForegin1
assignForegin2
unassignForegin2
In each one, I'm getting only 2 parameters - 1 id and 1 foreignId (after that I'm creating a User with the relevant fields out of it). Assign - if there is no id, I'm creating a new one with this foreignId, and if it exists, I override/assigning the new foreginId. Unassign - I'm removing the foreginId from this id, and if the id contains no foreginIds, I delete it.
So, assign is half PUT and half POST, and the unassign is half PUT and half DELETE.
What will be the best practice in this scenario?
Thanks
Upvotes: 2
Views: 71
Reputation: 3302
The API should follow single responsibility, it should only assign the foreign fields and should not create/delete if not present.
In your way, the end-user of the API doesn't know that you will delete the object if the object with id
doesn't have that foreignId
, he will also not know that a new object will be created if an object with an id
doesn't exist. As a best practice, the client of your API shouldn't know about your implementation.
I would suggest you divide the APIs into multiple CRUD APIs. Lets call your object as foreign
createForeign
type: POST
input: foreignId1, foreignId2
output: Foreign
assignForeignId1:
type: PUT
input: id, foreignId1
output: Foreign
assignForeignId2:
type: PUT
input: id, foreignId2
output: Foreign
In case the id doesn't exist in case of assignForeignId1
, the API should throw an error and the client should call createForeign
API if he wants to create one.
Upvotes: 1