Reputation: 1967
What is the preferred way of handling create and update request in a REST api?
On my frontend i am using the same form for both creating and updating, the only difference is that in case of update a hidden form field with id is filled.
Is it ok to send both requests to /api/post with POST method and based on the id decide whether to post or update? Or should this be handled otherwise?
Upvotes: 10
Views: 17030
Reputation: 2814
If you want to follow REST principles, separating the endpoint like below is preferred.
POST api/collections (e.g. api/users)
PUT api/collections/:id (e.g. api/users/23)
There are 2 reasons to separate the endpoint.
PUT has to be idempotent, while POST does not.
If the URL of the resource (like api/users/23) is already there, use PUT. If not, send POST and let the server generate URL. (In many cases, it uses DB’s auto-increment key)
Of course, it is up to you to decide whether you follow REST principles.
Reference https://restcookbook.com/HTTP%20Methods/put-vs-post/
Upvotes: 7