John
John

Reputation: 3402

In REST, how do you handle actions on a resources that don't fit cleanly into Get, Post, Put or Delete

So I'd like to create a commenting system, which will have an endpoint of something like:

mysite.com/comments/12345

So, I'd like the user who created the comment to be able to close off a comment, which would prevent any additional replies to the comment. Let's just say that the server method will be named "Close".

My question:

I will probably use ASP.Net Web API as the platform, though this is REST, so I assume that should have no bearing on the solution.

Upvotes: 0

Views: 195

Answers (2)

Tim
Tim

Reputation: 43314

Possible solution for your situation would be to add a field 'closed' or similar.
You probably already have a field user or author or something similar that specifies who is doing the request.

So when you create a comment

POST mysite.com/comments HTTP/1.1

{
  "body": "hey sway",
  "user": "John",
  "closed": "no"
}

This is using JSON and is just an example, I don't know how your server is implemented but that does not really matter.

Then, to 'close off' a comment you would do a PATCH (partial update) to that resource

PATCH mysite.com/comments/12345

{
  "closed": "yes"
}

Depending on how your server is implemented, providing only the fields that need to be updated/edited could be sufficient. However, because you only want the creator of the comment to be able to close it off, you should include user in the request as well:

PATCH mysite.com/comments/12345

{
  "user": "John"
  "closed": "yes"
}

Above example assumes the resource id for the created comment is 12345 like in your example.

Then on the server you can check if John is allowed to close the comment off.


So to sum it up

What does the url look like?

The url is the same as it would be for a GET

What does the body contain?

All the fields that need to be updated/edited, and user

What Http Verb do I use?

A PATCH makes the most sense here, since you are partially updating a resource.

Upvotes: 1

lefloh
lefloh

Reputation: 10961

If the information if a comment is closed is part of the resource you can PUT the new version of the resource:

PUT /comments/12345 HTTP/1.1

{
  "id" : "12345",
  "content" : "something",
  "replies" : [ "foo", "bar" ],
  "closed" : true
}

According to the HTTP Specification you must PUT the whole resource:

If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server.

If you don't want to send the whole resource you can use PATCH:

PATCH /comments/12345 HTTP/1.1

{ 
  "op" : "replace", 
  "path" : "/closed", 
  "value": true 
}

See the JSON Patch draft for more details.

You can also use POST for updating a resource. There are already lots of discussions about that like here, here and here.

Upvotes: 0

Related Questions