Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP Method to use for adding to a collection in a RESTful API

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"]
like image 941
driangle Avatar asked Jun 01 '12 18:06

driangle


People also ask

Which HTTP method is used to add new items to RESTful?

Method 1: POST POST is the only RESTful API HTTP method that primarily operates on resource collections. When creating a subordinate resource in a collection, applying POST to the parent resource prompts it to create a new resource, associate it with the proper hierarchy and return a dedicated URL for later reference.

Which HTTP method is used to get the resources in collection?

The HTTP GET method retrieves a resource representation. It is safe and idempotent. Repeated GET requests do not change any resources. The HTTP PUT method is often used to update resources or to create a new entity at a known URL.

What are the HTTP methods that can be used in RESTful web services?

In HTTP there are five methods that are commonly used in a REST-based Architecture i.e., POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations respectively.


2 Answers

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.

like image 113
alganet Avatar answered Sep 21 '22 01:09

alganet


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.

like image 35
Norman Joyner Avatar answered Sep 17 '22 01:09

Norman Joyner