HTTP verb GET or PATCH or POST or PUT when call increments views - http

I have an end point like this
/profiles/1
I want to get the profile whose id is 1 but at the same time increment the visited property by 1. The property comes as part of the object. Which HTTP verb I should be using to fetch the profile object with visited property incremented by 1.
Everytime a profile with id: 1 is fetched, the visited property will be incremented by 1.

Which HTTP verb I should be using to fetch the profile object with visited property incremented by 1?
The GET method is meant to be used for data retrieval, so it's a candidate. Quoting the RFC 7231, the document that currently defines the semantics and contents of the HTTP/1.1 protocol:
4.3.1. GET
The GET method requests transfer of a current selected representation for the target resource. GET is the primary mechanism of information retrieval and the focus of almost all performance optimizations. [...]
The GET method is also defined as both safe (read-only) and idempotent (multiple identical requests with that method is the same as the effect for a single such request).
But it's still on the table. Again, quoting the RFC 7231 (highlights are mine):
4.2.1. Safe Methods
Request methods are considered "safe" if their defined semantics are essentially read-only; i.e., the client does not request, and does not expect, any state change on the origin server as a result of applying a safe method to a target resource. [...]
This definition of safe methods does not prevent an implementation from including behavior that is potentially harmful, that is not entirely read-only, or that causes side effects while invoking a safe method. What is important, however, is that the client did not request that additional behavior and cannot be held accountable for it. For example, most servers append request information to access log files at the completion of every response, regardless of the method, and that is considered safe even though the log storage might become full and crash the server. [...]
4.2.2. Idempotent Methods
A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. [...]
Like the definition of safe, the idempotent property only applies to what has been requested by the user; a server is free to log each request separately, retain a revision control history, or implement other non-idempotent side effects for each idempotent request.
Assuming you want to count the number of the times a profile is retrieved, then it makes sense to attach it to the GET operation. You may want, however, to avoid incrementing the counter when the endpoint is hit by a bot, for example.
So under certain conditions, GET requests are allowed to have side effects. What is important, however, is that the client did not request that additional behavior and cannot be held accountable for it: what a server does is the server's responsibility.
Ultimately, it's also important to say that HTTP doesn't care about the storage underneath, so you could either store the view count in the same table as the profile data or a different table or a completely different database. And then retrieve all together or use different endpoints for the view count.

Related

what is difference between PUT and POST , why PUT is considered idempotent?

It is said everywhere[after reading many posts] that PUT is idempotent, means multiple requests with same inputs will produce same result as the very first request.
But, if we put same request with same inputs with POST method, then again, it will behave as PUT.
So, what is the difference in terms of Idempotent between PUT and POST.
The idea is that there should be a difference between POST and PUT, not that there is any. To clarify, the POST request should ideally create a new resource, whereas PUT request should be used to update the existing one. So, a client sending two POST requests would create two resources, whereas two PUT requests wouldn't (or rather shouldn't) cause any undesirable change.
To go into more detail, idempotency means that in an isolated environment multiple requests from the same client does not have any effect on the state of the resource. If request from another client changes the state of the resource, than it does not break the idempotency principle. Although, if you really want to ensure that put request does not end up overriding the changes by another simultaneous request from different client, you should always use etags. To elaborate, put request should always supply an etag (it got from get request) of the last resource state, and only if the etag is latest the resource should be updated, otherwise 412 (Precondition Failed) status code should be raised. In case of 412, client is suppose to get the resource again, and then try the update. According to REST, this is vital to prevent race conditions.
According to
W3C(http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html),
'Methods can also have the property of "idempotence" in that (aside
from error or expiration issues) the side-effects of N > 0 identical
requests is the same as for a single request.'

Choosing between safe and unsafe HTTP Method when creating MVC action

I'm generally following the recommendations when it comes to choosing between HTTP GET and HTTP POST as allowed method for action on controller in ASP.NET MVC.
When there is no change on server side, aka I want to retrieve a resource, HTTP GET is allowed.
When user is about to submit some data that will be persisted, HTTP POST is required.
Now here comes the issue with the gray zone:
What if user wants to download a file?
Usually I would set this as HTTP GET (file is stored in database due to security reasons) as there is no change done on the server.
What if I want to log that file X was downloaded by user Y?
There is now server-side change as new log is created. Is that a good enough reason to change HTTP method from GET to POST?
I've found exact explanation on how to deal with this:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
Definition of safe methods:
9.1.1 Safe Methods
Implementors should be aware that the software represents the user in
their interactions over the Internet, and should be careful to allow
the user to be aware of any actions they might take which may have an
unexpected significance to themselves or others.
In particular, the convention has been established that the GET and
HEAD methods SHOULD NOT have the significance of taking an action
other than retrieval. These methods ought to be considered "safe".
This allows user agents to represent other methods, such as POST, PUT
and DELETE, in a special way, so that the user is made aware of the
fact that a possibly unsafe action is being requested.
Naturally, it is not possible to ensure that the server does not
generate side-effects as a result of performing a GET request; in
fact, some dynamic resources consider that a feature. The important
distinction here is that the user did not request the side-effects, so
therefore cannot be held accountable for them.
Important part is emphasized below, which gives resolution to my problem:
Naturally, it is not possible to ensure that the server does not
generate side-effects as a result of performing a GET request; in
fact, some dynamic resources consider that a feature. The important
distinction here is that the user did not request the side-effects, so
therefore cannot be held accountable for them.
So since user did not request the logging to be performed, it is considered to be side-effect and therefore I can continue setting GET as HTTP method for file download.

Consequences of POST not being idempotent (RESTful API)

I am wondering if my current approach makes sense or if there is a better way to do it.
I have multiple situations where I want to create new objects and let the server assign an ID to those objects. Sending a POST request appears to be the most appropriate way to do that.
However since POST is not idempotent the request may get lost and sending it again may create a second object. Also requests being lost might be quite common since the API is often accessed through mobile networks.
As a result I decided to split the whole thing into a two-step process:
First sending a POST request to create a new object which returns the URI of the new object in the Location header.
Secondly performing an idempotent PUT request to the supplied Location to populate the new object with data. If a new object is not populated within 24 hours the server may delete it through some kind of batch job.
Does that sound reasonable or is there a better approach?
The only advantage of POST-creation over PUT-creation is the server generation of IDs.
I don't think it worths the lack of idempotency (and then the need for removing duplicates or empty objets).
Instead, I would use a PUT with a UUID in the URL. Owing to UUID generators you are nearly sure that the ID you generate client-side will be unique server-side.
well it all depends, to start with you should talk more about URIs, resources and representations and not be concerned about objects.
The POST Method is designed for non-idempotent requests, or requests with side affects, but it can be used for idempotent requests.
on POST of form data to /some_collection/
normalize the natural key of your data (Eg. "lowercase" the Title field for a blog post)
calculate a suitable hash value (Eg. simplest case is your normalized field value)
lookup resource by hash value
if none then
generate a server identity, create resource
Respond => "201 Created", "Location": "/some_collection/<new_id>"
if found but no updates should be carried out due to app logic
Respond => 302 Found/Moved Temporarily or 303 See Other
(client will need to GET that resource which might include fields required for updates, like version_numbers)
if found but updates may occur
Respond => 307 Moved Temporarily, Location: /some_collection/<id>
(like a 302, but the client should use original http method and might do automatically)
A suitable hash function might be as simple as some concatenated fields, or for large fields or values a truncated md5 function could be used. See [hash function] for more details2.
I've assumed you:
need a different identity value than a hash value
data fields used
for identity can't be changed
Your method of generating ids at the server, in the application, in a dedicated request-response, is a very good one! Uniqueness is very important, but clients, like suitors, are going to keep repeating the request until they succeed, or until they get a failure they're willing to accept (unlikely). So you need to get uniqueness from somewhere, and you only have two options. Either the client, with a GUID as Aurélien suggests, or the server, as you suggest. I happen to like the server option. Seed columns in relational DBs are a readily available source of uniqueness with zero risk of collisions. Round 2000, I read an article advocating this solution called something like "Simple Reliable Messaging with HTTP", so this is an established approach to a real problem.
Reading REST stuff, you could be forgiven for thinking a bunch of teenagers had just inherited Elvis's mansion. They're excitedly discussing how to rearrange the furniture, and they're hysterical at the idea they might need to bring something from home. The use of POST is recommended because its there, without ever broaching the problems with non-idempotent requests.
In practice, you will likely want to make sure all unsafe requests to your api are idempotent, with the necessary exception of identity generation requests, which as you point out don't matter. Generating identities is cheap and unused ones are easily discarded. As a nod to REST, remember to get your new identity with a POST, so it's not cached and repeated all over the place.
Regarding the sterile debate about what idempotent means, I say it needs to be everything. Successive requests should generate no additional effects, and should receive the same response as the first processed request. To implement this, you will want to store all server responses so they can be replayed, and your ids will be identifying actions, not just resources. You'll be kicked out of Elvis's mansion, but you'll have a bombproof api.
But now you have two requests that can be lost? And the POST can still be repeated, creating another resource instance. Don't over-think stuff. Just have the batch process look for dupes. Possibly have some "access" count statistics on your resources to see which of the dupe candidates was the result of an abandoned post.
Another approach: screen incoming POST's against some log to see whether it is a repeat. Should be easy to find: if the body content of a request is the same as that of a request just x time ago, consider it a repeat. And you could check extra parameters like the originating IP, same authentication, ...
No matter what HTTP method you use, it is theoretically impossible to make an idempotent request without generating the unique identifier client-side, temporarily (as part of some request checking system) or as the permanent server id. An HTTP request being lost will not create a duplicate, though there is a concern that the request could succeed getting to the server but the response does not make it back to the client.
If the end client can easily delete duplicates and they don't cause inherent data conflicts it is probably not a big enough deal to develop an ad-hoc duplication prevention system. Use POST for the request and send the client back a 201 status in the HTTP header and the server-generated unique id in the body of the response. If you have data that shows duplications are a frequent occurrence or any duplicate causes significant problems, I would use PUT and create the unique id client-side. Use the client created id as the database id - there is no advantage to creating an additional unique id on the server.
I think you could also collapse creation and update request into only one request (upsert). In order to create a new resource, client POST a “factory” resource, located for example at /factory-url-name. And then the server returns the URI for the new resource.
Why don't you use a request Id on your originating point (your originating point should do two things, send a GET request on request_id=2 to see if it's request has been applied - like a response with person created and created as part of request_id=2
This will ensure your originating system knows what was the last request that was executed as the request id is stored in db.
Second thing, if your originating point finds that last request was still at 1 not yet 2, then it may try again with 3, to make sure if by any chance just the GET response has gotten lost but the request 2 was created in the db.
You can introduce number of tries for your GET request and time to wait before firing again a GET etc kinds of system.

What is the usefulness of PUT and DELETE HTTP request methods?

I've never used PUT or DELETE HTTP Request methods. My tendency is to use GET when the state of the system (my application or website) may not be affected (like a product listing) and to use POST when it is affected (like placing an order). Aren't those two always sufficient, or am I missing something?
DELETE is for deleting the request resource:
The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully …
PUT is for putting or updating a resource on the server:
The PUT method requests that the enclosed entity be stored under the supplied Request-URI. 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 the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI …
For the full specification visit:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
Since current browsers unfortunately do not support any other verbs than POST and GET in HTML forms, you usually cannot utilize HTTP to it's full extent with them (you can still hijack their submission via JavaScript though). The absence of support for these methods in HTML forms led to URIs containing verbs, like for instance
POST http://example.com/order/1/delete
or even worse
POST http://example.com/deleteOrder/id/1
effectively tunneling CRUD semantics over HTTP. But verbs were never meant to be part of the URI. Instead HTTP already provides the mechanism and semantics to CRUD a Resource (e.g. an order) through the HTTP methods. HTTP is a protocol and not just some data tunneling service.
So to delete a Resource on the webserver, you'd call
DELETE http://example.com/order/1
and to update it you'd call
PUT http://example.com/order/1
and provide the updated Resource Representation in the PUT body for the webserver to apply then.
So, if you are building some sort of client for a REST API, you will likely make it send PUT and DELETE requests. This could be a client built inside a browser, e.g. sending requests via JavaScript or it could be some tool running on a server, etc.
For some more details visit:
http://martinfowler.com/articles/richardsonMaturityModel.html
Are the PUT, DELETE, HEAD, etc methods available in most web browsers?
Why are there no PUT and DELETE methods in HTML forms
Should PUT and DELETE be used in forms?
http://amundsen.com/examples/put-delete-forms/
http://www.quora.com/HTTP/Why-are-PUT-and-DELETE-no-longer-supported-in-HTML5-forms
Using HTTP Request verb such as GET, POST, DELETE, PUT etc... enables you to build RESTful web applications. Read about it here: http://en.wikipedia.org/wiki/Representational_state_transfer
The easiest way to see benefits from this is to look at this example.
Every MVC framework has a Router/Dispatcher that maps URL-s to actionControllers.
So URL like this: /blog/article/1 would invoke blogController::articleAction($id);
Now this Router is only aware of the URL or /blog/article/1/
But if that Router would be aware of whole HTTP Request object instead of just URL, he could have access HTTP Request verb (GET, POST, PUT, DELETE...), and many other useful stuff about current HTTP Request.
That would enable you to configure application so it can accept the same URL and map it to different actionControllers depending on the HTTP Request verb.
For example:
if you want to retrive article 1 you can do this:
GET /blog/article/1 HTTP/1.1
but if you want to delete article 1 you will do this:
DELETE /blog/article/1 HTTP/1.1
Notice that both HTTP Requests have the same URI, /blog/article/1, the only difference is the HTTP Request verb. And based on that verb your router can call different actionController. This enables you to build neat URL-s.
Read this two articles, they might help you:
Symfony 2 - HTTP Fundamentals
Symfony 2 - Routing
These articles are about Symfony 2 framework, but they can help you to figure out how does HTTP Requests and Responses work.
Hope this helps!
Although I take the risk of not being popular I say they are not useful nowadays.
I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.
Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.
Let's take an example:
/api/entity/list/{id} vs GET /api/entity/{id}
/api/entity/add/{id} vs POST /api/entity
/api/entity/edit/{id} vs PUT /api/entity/{id}
/api/entity/delete/{id} vs DELETE /api/entity/{id}
On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.
Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.
In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.
Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards
Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times
According to your requirement :
1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD
See the accepted answer from #Gordon, the key point being simply this:
PUT and DELETE are specific verbs with a meaning, that instruct the server to do something specific and how the instruction should be handled.
OK standards and semantics are great but what real use is DELETE to me if all I want to do is somehow run code to delete something from a database?
So what if we say, "OK but it's easier for me to just do a delete by issuing a GET to my URI that has a path /api/entity/delete/{id} (as suggested in the answer by #Bogdan). OK so let's look at the definition of GET:
The GET method means retrieve whatever information (in the form of an
entity) is identified by the Request-URI
Source - W3C standards - https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
If you use GET for a DELETE you are clearly misusing the method according to its standard definition.
Alright so let's further say 'OK but that doesn't really matter because it's just more practical for a developer to read a URI somewhere that uses a GET method and reads /api/entity/delete/{id} instead of having a DELETE method that deletes resources having the same signature as a GET method that retrieves, so that the developer understands that's meant for deletion. Let's consider a well structured DELETE method signature (example is for .NET Core 5):
// DELETE: api/TodoItems/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteTodoItem(long id)
{
This will not respond to a get request, (so for example, accidental deletion instead of retrieval when making a call to the API is more protected - the developer has to explicitly perform a DELETE request to the API). And we have a very clear, well structured and named API operation that's clear and highly discoverable by a developer or even automated tooling (e.g. a developer can now search specifically for any occurrence of DELETE in code, or for the method name which clearly indicates the DELETE). And what's more, this pattern conforms to a generally accepted standard for a 'RESTFUL' API that should render the API more broadly recognisable and interpretable to developers (and potentially any automated tooling).
OK, that's nice, but what's the real difference in making it a DELETE? Why even use DELETE instead of GET? My operation is deleting something from the database, why should my web server care? OK, let's think about the definition of DELETE:
9.7 DELETE - The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be
overridden by human intervention (or other means) on the origin
server.
So now, if we're specifying a delete, we have the potential for specific behaviour on the server that potentially allows for reversing a delete action by manual or automatic intervention. In a particular use case, that could be significant.
OK well DELETE works for me then, but why use PUT? For example it's more convenient if I just make an 'upsert' method that uses POST, and update the resource if it exists or create it if it doesn't
I personally typically do this when I"m implementing an API that effects operations against a database, although again there is specific meaning to PUT i.e. that it specifically indicates updating of a resource, while POST indicates creation, so using POST for both creating and updating is counter-standard. My own view is that a REST API is a case when I typically view the practicality of upsert functionality as being more important that strict use of the correct verb for adds versus insert, but I could be missing something here.
Use of PUT outside of a REST api could be more significant for practical purposes, for example if we're performing an update operation where the server can potentially clear any cacheing by understanding that the resource has been updated (which is more significant if our resource is a whole document, for example). There may be some practical advantages I haven't considered when PUT is utilised inside a restful API for an update operation.
The standard definition for POST states that a POST success response SHOULD be 201 (created), and not just the generic '200 OK', so that we're able to correctly interpret that resource creation is explicitly successful. That response isn't appropriate for an update operation but there's no 'MUST' specified in the standard for the response code. It's certainly common for developers to use POST for an upsert and return 200 (OK) on success, whether it's a creation or an update.
The standard for PUT is more strict, and specifies that any unexpected creation of a resource when attempting an update MUST be indicated via a 201 response code. This can occur if no existing resource exists at the specified URI. The standard explains that if we use PUT we get clearer feedback on whether the result of our attempted update operation is what we expected.
From the W3C standard:
[if a put] does not point to an existing resource, and that URI is
capable of being defined as a new resource by the requesting user
agent, the origin server can create the resource with that URI. If a
new resource is created, the origin server MUST inform the user agent
via the 201 (Created) response. If an existing resource is modified,
either the 200 (OK) or 204 (No Content) response codes SHOULD be sent
to indicate successful completion of the request.
PUT
The PUT method is used whenever you need to change the resource. The resource, which is already a part of resource collection. One thing to note here is that PUT method modifies the entire resource whereas PATCH method is used to modify the necessary part of the resource or data.
DELETE
As the name says, the DELETE request method is used to delete the specified resource. It requests that the origin server delete the resource identified by the Request-URL.
I hope this simple definitions help.

RESTful view counter

I would like to count the access to a resource, but HTTP GET should not modify a resource. The counter should be displayed with the resource. A similar case would be to store the last access.
What is the REST way to realize a view counter?
Updating a counter in reaction to a GET is actually not a violation of the HTTP protocol. You are not modifying the resource you are getting, or any other resource that the client can control.
If a server was not allowed to do any updates in response to a GET then log files would violate the HTTP contract!
Here is the relevant part in RFC2616,:
9.1.1 Safe Methods
Implementors should be aware that the
software represents the user in their
interactions over the Internet, and
should be careful to allow the user to
be aware of any actions they might
take which may have an unexpected
significance to themselves or others.
In particular, the convention has been
established that the GET and HEAD
methods SHOULD NOT have the
significance of taking an action other
than retrieval. These methods ought to
be considered "safe". This allows user
agents to represent other methods,
such as POST, PUT and DELETE, in a
special way, so that the user is made
aware of the fact that a possibly
unsafe action is being requested.
Naturally, it is not possible to
ensure that the server does not
generate side-effects as a result of
performing a GET request; in fact,
some dynamic resources consider that a
feature. The important distinction
here is that the user did not request
the side-effects, so therefore cannot
be held accountable for them.
The first significant thing to note is that it says "SHOULD NOT" and not "MUST NOT". There are cases where side effects are valid.
The second critical line is last line that highlights the fact that the user did not make a request with any desire to make a change and therefore it is up to the server to ensure that nothing happens that would be contradictory to the clients expectations. This is the essence of the "uniform interface constraint". The server should do what the client expects. This is very different than the client issuing
GET /myresource?operation=delete
In this case, the client thinks they are doing a retrieval. If the client application is respecting the hypermedia constraint then the contents of URL are completely opaque, so the only information the client can understand is the verb GET. If the server actually does a delete then, that is a clear violation of the uniform interface constraint.
Updating an internal counter is not a violation of the uniform interface constraint. If the counter was to be included in the representation being retrieved then you have a whole new set of problems, but I am going to assume that is not the case.

Resources