ChatGPT解决这个技术问题 Extra ChatGPT

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?

PUT/DELETE is easier to code, but harder to setup (security wise - vhost/apache directory). My humble opinion... you can live without those.
@Najzero yes I am extremely happy without them :) but need some answer on why they are there ?? have read some stuff but couldn't cop it
See also stackoverflow.com/questions/630453/… - the accepted answer has a good discussion about POST vs PUT

C
Community

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


Browsers can send PUT and DELETE with JavaScript!
@Joe Yes, but HTML form methods do not. And as long as that isn't supported out of the box, you have to go through hoops to make it work. It's one of the major fails of browser vendors.
Of course they don't, forms are designed for POST and GET. That is in the design HTML. It it not true to say that PUT and DELETE is not supported though. Browsers implement HTML and HTTP.
The browser displays an empty page unless you write some HTML. Yes, perhaps we have to disagree. Disagreeing is ok!
For instance, DELETE can do stuff like invalidate cached versions of the URI. With a POST-based API, any proxy you use either has to know what your API does (bad) or be turned off completely (also bad). And that's why we use standards. :) (Though it'd admittedly be nice if forms had a way to bind DELETE to a submit button.)
k
kamal pal

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!


This answer explains it best to describe the importance of the HTTP verbs and keeping in line with truly RESTful services and their benefits. If you don't use say a HTTP DELETE, then you might have (2) POST actions in a controller: 1 for Create and 1 for Delete. If you do this, your very next search will be for "How to have multiple Post actions in a single controller" :P. Not that this is awful, but you loose the ability to have a unique resource be implemented via the verb action as opposed to having to explicitly provide the action name in the URI.
B
Bogdan

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


Reasonable arguments but the semantics of dedicated methods for actions outweighs the 'convenience' of naming methods via the URL. If you POST or event GET to do a DELETE, you're simply misusing HTTP methods that are clearly defined respectively as methods to create a new resource and retrieve an existing resource. Use integration tests to ensure a junior dev can't alter API behaviour. I'm generally wary of things that make it 'convenient' for developers - they're often the first sign of code smell or lower quality development. Also Url rewriting does nothing to change a protocol definition??
@ChrisHalcrow agree with you point of view but programmers are humans, not robots, and they tend to go for convenient. I like standards, definitions, etc... and I like to follow them but only as long as they are reasonable practically to do so
Using standard verbs for the operations is definitely 'reasonably practical'. So is understanding/habit that GET means 'retrieve' (with ID parameter included) or 'list' (if it's not), POST means add (it's even reasonably acceptable for POST to mean 'upsert' or 'update', but only as a complete overwrite of the data). And DELETE is self explanatory. I don't see anything impractical about that. For example, if you somehow generate or scaffold a restful API, tooling is much more likely by default to generate a fairly standard 'RESTFUL' structure for the URLs, using correct verbs.
I'd recommend to differentiate between the route naming (URL) and operation name. So it's possible to specify DELETE /api/entity/{id} as the route that invokes the method, and the operation can be encapsulated in either a unit of work e.g. myEntity.Delete(), or in a method DeleteEntity(). Then it has to be clear and discoverable to anyone.
The main issue I have is your statement that both PUT and DELETE are not useful. The standard states that GET should return an identified resource. POST is a non-idempotent action where the resulting resource should be a subordinate of the Uri used in the POST. Neither should be used for a delete. Also there's no logical link I can see that URL rewriting should make PUT or DELETE redundant. URL redirection is just forwarding to a URI that should honour HTTP standards. The main concept of good 'RESTFUL' design is honouring what's expected by HTTP standards in an API implementation.
u
user1953168

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


C
Chris Halcrow

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.


P
Pratham

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.