HTTP Method to use for adding to a collection in a

2020-07-14 09:45发布

问题:

I have a resource that represents a collection of tags:

/users/{username}/tags

An API client should be able to add a set of tags to this collection in a single HTTP request. I thought about how to do this and first thought about using the PUT or POST methods. However I think this would imply that the client is "setting" or "replacing" the tags in that collection. What would be the most appropriate HTTP method (or perhaps a different mechanism) to "add" multiple tags to that collection?

{HTTP METHOD} /users/{username}/tags

Request Body:

 ["short", "crazy", "funny"]

回答1:

If the tags being sent in the request body are intended to be added to a collection, rather than replace, I would suggest POST. If you intend to replace the existing tags, use PUT.



回答2:

PUT /users/alganet/tags replaces all the tags.

POST /users/alganet/tags adds more tags.

You can also use PATCH.

PATCH /users/alganet/tags changes tags.

Possible body:

{"POST":["rest", "php"], "DELETE":["soap"]}

The body must have a specific patch format matching the Accept-Patch header. The sample body above is a custom format for patches, but you could use a clean diff for example.