简体   繁体   中英

Rest API for both create and update

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM