What is the difference between PUT, POST and PATCH? - http

What is the difference between PUT, POST and PATCH methods in HTTP protocol?

Difference between PUT, POST, GET, DELETE and PATCH in HTTP Verbs:
The most commonly used HTTP verbs POST, GET, PUT, DELETE are similar to CRUD (Create, Read, Update and Delete) operations in database. We specify these HTTP verbs in the capital case. So, the below is the comparison between them.
Create - POST
Read - GET
Update - PUT
Delete - DELETE
PATCH: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH method.
Note:
Since POST, PUT, DELETE modifies the content, the tests with Fiddler for the below url just mimicks the updations. It doesn't delete or modify actually. We can just see the status codes to check whether insertions, updations, deletions occur.
URL: http://jsonplaceholder.typicode.com/posts/
GET:
GET is the simplest type of HTTP request method; the one that browsers use each time you click a link or type a URL into the address bar. It instructs the server to transmit the data identified by the URL to the client. Data should never be modified on the server side as a result of a GET request. In this sense, a GET request is read-only.
Checking with Fiddler or PostMan:
We can use Fiddler for checking the response. Open Fiddler and select the Compose tab.
Specify the verb and url as shown below and click Execute to check the response.
Verb: GET
url: http://jsonplaceholder.typicode.com/posts/
Response: You will get the response as:
"userId": 1, "id": 1, "title": "sunt aut...", "body": "quia et suscipit..."
In the “happy” (or non-error) path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).
2) POST:
The POST verb is mostly utilized to create new resources. In particular, it's used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource.
On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status.
Checking with Fiddler or PostMan:
We can use Fiddler for checking the response. Open Fiddler and select the Compose tab.
Specify the verb and url as shown below and click Execute to check the response.
Verb: POST
url: http://jsonplaceholder.typicode.com/posts/
Request Body:
data: {
title: 'foo',
body: 'bar',
userId: 1000,
Id : 1000
}
Response: You would receive the response code as 201.
If we want to check the inserted record with Id = 1000 change the verb to Get and use the same url and click Execute.
As said earlier, the above url only allows reads (GET), we cannot read the updated data in real.
3) PUT:
PUT is most-often utilized for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.
Checking with Fiddler or PostMan:
We can use Fiddler for checking the response. Open Fiddler and select the Compose tab.
Specify the verb and url as shown below and click Execute to check the response.
Verb: PUT
url: http://jsonplaceholder.typicode.com/posts/1
Request Body:
data: {
title: 'foo',
body: 'bar',
userId: 1,
Id : 1
}
Response: On successful update it returns status 200 (or 204 if not returning any content in the body) from a PUT.
4) DELETE:
DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.
On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body. In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.
Checking with Fiddler or PostMan:
We can use Fiddler for checking the response. Open Fiddler and select the Compose tab.
Specify the verb and url as shown below and click Execute to check the response.
Verb: DELETE
url: http://jsonplaceholder.typicode.com/posts/1
Response: On successful deletion it returns HTTP status 200 (OK) along with a response body.
Example between PUT and PATCH
PUT
If I had to change my first name then send PUT request for Update:
{ "first": "Nazmul", "last": "hasan" }
So, here in order to update the first name we need to send all the parameters of the data again.
PATCH:
Patch request says that we would only send the data that we need to modify without modifying or effecting other parts of the data.
Ex: if we need to update only the first name, we pass only the first name.
Please refer the below links for more information:
https://jsonplaceholder.typicode.com/
https://github.com/typicode/jsonplaceholder#how-to
What is the main difference between PATCH and PUT request?
http://www.restapitutorial.com/lessons/httpmethods.html

The below definition is from the real world example.
Example Overview
For every client data, we are storing an identifier to find that client data and we will send back that identifier to the client for reference.
POST
If the client sends data without any identifier, then we will store the data and assign/generate a new identifier.
If the client again sends the same data without any identifier, then we will store the data and assign/generate a new identifier.
Note: Duplication is allowed here.
PUT
If the client sends data with an identifier, then we will check whether that identifier exists. If the identifier exists, we will update the resource with the data, else we will create a resource with the data and assign/generate a new identifier.
PATCH
If the client sends data with an identifier, then we will check whether that identifier exists. If the identifier exists, we will update the resource with the data, else we will throw an exception.
Note: On the PUT method, we are not throwing an exception if an identifier is not found. But in the PATCH method, we are throwing an exception if the identifier is not found.
Do let me know if you have any queries on the above.

Here is a simple description of all:
POST is always for creating a resource ( does not matter if it was duplicated )
PUT is for checking if resource exists then update, else create new resource
PATCH is always for updating a resource

PUT = replace the ENTIRE RESOURCE with the new representation provided
PATCH = replace parts of the source resource with the values provided AND|OR other parts of the resource are updated that you havent provided (timestamps) AND|OR updating the resource effects other resources (relationships)
https://laracasts.com/discuss/channels/general-discussion/whats-the-differences-between-put-and-patch?page=1

Simplest Explanation:
POST - Create NEW record
PUT - If the record exists, update else, create a new record
PATCH - update
GET - read
DELETE - delete

Think of it this way...
POST - create
PUT - replace
PATCH - update
GET - read
DELETE - delete

Request Types
create - POST
read - GET
create or update - PUT
delete - DELETE
update - PATCH
GET/PUT is idempotent
PATCH can be sometimes idempotent
What is idempotent -
It means if we fire the query multiple times it should not afftect the result of it.(same output.Suppose a cow is pregnant and if we breed it again then it cannot be pregnent multiple times)
get :-
simple get. Get the data from server and show it to user
{
id:1
name:parth
email:x#x.com
}
post :-
create new resource at Database. It means it adds new data. Its not idempotent.
put :-
Create new resource otherwise add to existing.
Idempotent because it will update the same resource everytime and output will be the same.
ex.
- initial data
{
id:1
name:parth
email:x#x.com
}
perform put-localhost/1
put email:ppp#ppp.com
{
id:1
email:ppp#ppp.com
}
patch
so now came patch request
PATCH can be sometimes idempotent
id:1
name:parth
email:x#x.com
}
patch name:w
{
id:1
name:w
email:x#x.com
}
HTTP Method
GET yes
POST no
PUT yes
PATCH no*
OPTIONS yes
HEAD yes
DELETE yes
Resources :
Idempotent -- What is Idempotency?

Main Difference Between PUT and PATCH Requests:
Suppose we have a resource that holds the first name and last name of a person.
If we want to change the first name then we send a put request for Update
{ "first": "Michael", "last": "Angelo" }
Here, although we are only changing the first name, with PUT request we have to send both parameters first and last.
In other words, it is mandatory to send all values again, the full payload.
When we send a PATCH request, however, we only send the data which we want to update. In other words, we only send the first name to update, no need to send the last name.

Quite logical the difference between PUT & PATCH w.r.t sending full & partial data for replacing/updating respectively. However, just couple of points as below
Sometimes POST is considered as for updates w.r.t PUT for create
Does HTTP mandates/checks for sending full vs partial data in PATCH? Otherwise, PATCH may be quite same as update as in PUT/POST

You may understand the restful HTTP methods as corresponding operations on the array in javascript (with index offset by 1).
See below examples:
Method
Url
Meaning
GET
/users
return users array
GET
/users/1
return users[1] object
POST
/users
users.push(body); return last id or index
PUT
/users
replace users array
PUT
/users/1
users[1] = body
PATCH
/users/1
users[1] = {...users[1], ...body }
DELETE
/users/1
delete users[1]

Reference to RFC: https://www.rfc-editor.org/rfc/rfc9110.html#name-method-definitions
POST - creates new object
PUT - updates old object or creates new one if not exist
PATCH - updates/modify old object. Primarly intended for for modificaiton.
There is few interpritation of RFC like mentioned before, but if you read carefully then you can notice that PUT and PATCH methods came after POST witch is common old fashion way to create native HTML Forms.
Therefore if you try to support all methods (like PATCH or DELETE), it can be suggested that the most approapreate way to use all methods is to stick to CRUD model:
Create - PUT
Read - GET
Update - PATCH
Delete - DELETE
Old HTML native way:
Read - GET
Create/Update/Delete - POST
Good Luck Coders! ;-)

Related

What is the meaning of "contain an entity which describes the status of the request and refers to the new resource" in the HTTP/1.1 spec?

Chapter 9.5 POST of the HTTP/1.1 spec includes the sentence:
If a resource has been created on the origin server, the response
SHOULD be 201 (Created) and contain an entity which describes the
status of the request and refers to the new resource, and a Location
header
It is referenced frequently. The itention is clear, but I have issues with the meaning of some of the chosen words.
What does "contain an entity which describes the status of the request and refers to the new resource" exactly mean?
How shall the entity (entity-header fields and entity-body) describe the status of the request? Isn't the status of the request 201 (Created)? Whow shall this status be described? Does "describe the status of the request" mean the result, in other words the current entity status?
Thinking of a Web API with JSON representation does it mean that the entity should be included in a JSON representation after a successful POST that created an entity? Thinking of a created image, should the image data be returned in the response body?
What is meant with refers to the new resource? The uri is already in the location header. Shall it be repeated in the body or does it mean just to add an id?
Is there a good source with examples of different entities and its responses to a creation POST?
I think it varies based on the resource you're creating, suppose your posting to a /profile/ resource maybe a payload containing multiple profile fields to update - your return would indicate it was successful and include a reference to the fields you posted (it can even return the entire profile attributes with fields you've updated including all fields);
Another example in the image sense, suppose you are posting a Base64 encoded image to a service that stores the image, the response should show the status (ie: accepted, rejected, file too larage, MIME type accurate or not, etc.) - and within the returned payload if successful you'd want the response to not be vague but return the path and/or filename of the image uploaded;
The header returns the response code - the body returns information related to the invoked action's entity response (it can be a set of fields, a URL, a useful response that when parsed back it can be actionable or informative);
These are principles of good coding, but also keep note of security and not to expose anything in a return that could potentially be damaging for example; when creating a service you want to be clear and provide concise and useful returns so when the client consumes the API it knows what to do, what to expect, etc.

Response code for HTTP PUT with empty data

What is the most common/industry standard response code for HTTP PUT when:
Client made a well-formed request and
The content of the file/message/data is empty and
Because of that nothing has been changed on the server/in the database
In my specific case the client sends HTTP PUT with an empty JSON like this:
{}
while I expect something more like this:
{
key1: {
something: value,
something2:value2
},
key2: {
something: value3,
something: value4
}
}
which in my case would translate to 4 new rows being upserted to the database.
I am considering either 400 (because maybe it is a bad request when you call a HTTP PUT but you don't have anything to put there), 200, 204 and 304.
My question is different from this and this because they are about HTTP GET method, and is different from this because while it is about HTTP PUT the answer doesn't address my case.
A PUT request should replace what was on the server at the specified uri.
So if the resource at the uri already was empty, and the new resource that's being put is also empty, nothing changed but it's still a success, so 200 OK is fine.
If the resource didn't exist and you create a new 0-byte resource, 201 Created might be more appropriate.
If the resource did exist but it was not empty, and you send an empty PUT request, it should replace the existing resource with an empty one.
This is where you are going wrong, because PUT should not be used for a per-record "upsert" like you are doing.
If the PUT request you state was semantically correct, it should wipe out all existing records tied to that location.
What you probably want is PATCH or POST.

How to reuse variables from previous request in the Paw rest client?

I need to reuse value which is generated for my previous request.
For example, at first request, I make a POST to the URL /api/products/{UUID} and get HTTP response with code 201 (Created) with an empty body.
And at second request I want to get that product by request GET /api/products/{UUID}, where UUID should be from the first request.
So, the question is how to store that UUID between requests and reuse it?
You can use the Request Sent Dynamic values https://paw.cloud/extensions?extension_type=dynamic_value&q=request+send these will get the value used last time you sent a requst for a given request.
In your case you will want to combine the URLSentValue with the RegExMatch (https://paw.cloud/extensions/RegExMatch) to first get the url as it was last sent for a request and then extract the UUID from the url.
e.g
REQUEST A)
REQUEST B)
The problem is in your first requests answer. Just dont return "[...] an empty body."
If you are talking about a REST design, you will return the UUID in the first request and the client will use it in his second call: GET /api/products/{UUID}
The basic idea behind REST is, that the server doesn't store any informations about previous requests and is "stateless".
I would also adjust your first query. In general the server should generate the UUID and return it (maybe you have reasons to break that, then please excuse me). Your server has (at least sometimes) a better random generator and you can avoid conflicts. So you would usually design it like this:
CLIENT: POST /api/products/ -> Server returns: 201 {product_id: UUID(1234...)}
Client: GET /api/products/{UUID} -> Server returns: 200 {product_detail1: ..., product_detail2: ...}
If your client "loses" the informations and you want him to be later able to get his products, you would usually implement an API endpoint like this:
Client: GET /api/products/ -> Server returns: 200 [{id:UUID(1234...), title:...}, {id:UUID(5678...),, title:...}]
Given something like this, presuming the {UUID} is your replacement "variable":
It is probably so simple it escaped you. All you need to do is create a text file, say UUID.txt:
(with sample data say "12345678U910" as text in the file)
Then all you need to do is replace the {UUID} in the URL with a dynamic token for a file. Delete the {UUID} portion, then right click in the URL line where it was and select
Add Dynamic Value -> File -> File Content :
You will get a drag-n-drop reception widget:
Either press the "Choose File..." or drop the file into the receiver widget:
Don't worry that the dynamic variable token (blue thing in URL) doesn't change yet... Then click elsewhere to let the drop receiver go away and you will have exactly what you want, a variable you can use across URLs or anywhere else for that matter (header fields, form fields, body, etc):
Paw is a great tool that goes asymptotic to awesome when you explore the dynamic value capability. The most powerful yet I have found is the regular expression parsing that can parse raw reply HTML and capture anything you want for the next request... For example, if you UUID came from some user input and was ingested into the server, then returned in a html reply, you could capture that from the reply HTML and re-inject it to the URL, or any field or even add it to the cookies using the Dynamic Value capabilities of Paw.
#chickahoona's answer touches on the more normal way of doing it, with the first request posting to an endpoint without a UUID and the server returning it. With that in place then you can use the RegExpMatch extension to extract the value from the servers's response and use it in subsequent requests.
Alternately, if you must generate the UUID on the client side, then again the RegExpMatch extension can help, simply choose the create request's url for the source and provide a regexp that will strip the UUID off the end of it, such as /([^/]+)$.
A third option I'll throw out to you, put the UUID in an environment variable and just have all of your requests reference it from there.

Should I use PATCH or PUT in my REST API?

I want to design my rest endpoint with the appropriate method for the following scenario.
There is a group. Each group has a status. The group can be activated or inactivated by the admin.
Should I design my end point as
PUT /groups/api/v1/groups/{group id}/status/activate
OR
PATCH /groups/api/v1/groups/{group id}
with request body like
{action:activate|deactivate}
The PATCH method is the correct choice here as you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety.
Further information on partial resource modification is available in RFC 5789. Specifically, the PUT method is described as follows:
Several applications extending the Hypertext Transfer Protocol
(HTTP) require a feature to do partial resource modification. The
existing HTTP PUT method only allows a complete replacement of a
document. This proposal adds a new HTTP method, PATCH, to modify an
existing HTTP resource.
The R in REST stands for resource
(Which isn't true, because it stands for Representational, but it's a good trick to remember the importance of Resources in REST).
About PUT /groups/api/v1/groups/{group id}/status/activate: you are not updating an "activate". An "activate" is not a thing, it's a verb. Verbs are never good resources. A rule of thumb: if the action, a verb, is in the URL, it probably is not RESTful.
What are you doing instead? Either you are "adding", "removing" or "updating" an activation on a Group, or if you prefer: manipulating a "status"-resource on a Group. Personally, I'd use "activations" because they are less ambiguous than the concept "status": creating a status is ambiguous, creating an activation is not.
POST /groups/{group id}/activation Creates (or requests the creation of) an activation.
PATCH /groups/{group id}/activation Updates some details of an existing activation. Since a group has only one activation, we know what activation-resource we are referring to.
PUT /groups/{group id}/activation Inserts-or-replaces the old activation. Since a group has only one activation, we know what activation-resource we are referring to.
DELETE /groups/{group id}/activation Will cancel, or remove the activation.
This pattern is useful when the "activation" of a Group has side-effects, such as payments being made, mails being sent and so on. Only POST and PATCH may have such side-effects. When e.g. a deletion of an activation needs to, say, notify users over mail, DELETE is not the right choice; in that case you probably want to create a deactivation resource: POST /groups/{group_id}/deactivation.
It is a good idea to follow these guidelines, because this standard contract makes it very clear for your clients, and all the proxies and layers between the client and you, know when it is safe to retry, and when not. Let's say the client is somewhere with flaky wifi, and its user clicks on "deactivate", which triggers a DELETE: If that fails, the client can simply retry, until it gets a 404, 200 or anything else it can handle. But if it triggers a POST to deactivation it knows not to retry: the POST implies this.
Any client now has a contract, which, when followed, will protect against sending out 42 emails "your group has been deactivated", simply because its HTTP-library kept retrying the call to the backend.
Updating a single attribute: use PATCH
PATCH /groups/{group id}
In case you wish to update an attribute. E.g. the "status" could be an attribute on Groups that can be set. An attribute such as "status" is often a good candidate to limit to a whitelist of values. Examples use some undefined JSON-scheme:
PATCH /groups/{group id} { "attributes": { "status": "active" } }
response: 200 OK
PATCH /groups/{group id} { "attributes": { "status": "deleted" } }
response: 406 Not Acceptable
Replacing the resource, without side-effects use PUT.
PUT /groups/{group id}
In case you wish to replace an entire Group. This does not necessarily mean that the server actually creates a new group and throws the old one out, e.g. the ids might remain the same. But for the clients, this is what PUT can mean: the client should assume he gets an entirely new item, based on the server's response.
The client should, in case of a PUT request, always send the entire resource, having all the data that is needed to create a new item: usually the same data as a POST-create would require.
PUT /groups/{group id} { "attributes": { "status": "active" } }
response: 406 Not Acceptable
PUT /groups/{group id} { "attributes": { "name": .... etc. "status": "active" } }
response: 201 Created or 200 OK, depending on whether we made a new one.
A very important requirement is that PUT is idempotent: if you require side-effects when updating a Group (or changing an activation), you should use PATCH. So, when the update results in e.g. sending out a mail, don't use PUT.
I would recommend using PATCH, because your resource 'group' has many properties but in this case, you are updating only the activation field(partial modification)
according to the RFC5789 (https://www.rfc-editor.org/rfc/rfc5789)
The existing HTTP PUT method only allows a complete replacement of
a document. This proposal adds a new HTTP method, PATCH, to modify
an existing HTTP resource.
Also, in more details,
The difference between the PUT and PATCH requests is reflected in the
way the server processes the enclosed entity to modify the resource
identified by the Request-URI. In a PUT request, the enclosed entity
is considered to be a modified version of the resource stored on the
origin server, and the client is requesting that the stored version
be replaced. With PATCH, however, the enclosed entity contains a set
of instructions describing how a resource currently residing on the
origin server should be modified to produce a new version. The PATCH
method affects the resource identified by the Request-URI, and it
also MAY have side effects on other resources; i.e., new resources
may be created, or existing ones modified, by the application of a
PATCH.
PATCH is neither safe nor idempotent as defined by [RFC2616],
Section
9.1.
Clients need to choose when to use PATCH rather than PUT. For
example, if the patch document size is larger than the size of the
new resource data that would be used in a PUT, then it might make
sense to use PUT instead of PATCH. A comparison to POST is even more
difficult, because POST is used in widely varying ways and can
encompass PUT and PATCH-like operations if the server chooses. If
the operation does not modify the resource identified by the Request-
URI in a predictable way, POST should be considered instead of PATCH
or PUT.
The response code for PATCH is
The 204 response code is used because the response does not carry a
message body (which a response with the 200 code would have). Note
that other success codes could be used as well.
also refer thttp://restcookbook.com/HTTP%20Methods/patch/
Caveat: An API implementing PATCH must patch atomically. It MUST not
be possible that resources are half-patched when requested by a GET.
Since you want to design an API using the REST architectural style you need to think about your use cases to decide which concepts are important enough to expose as resources. Should you decide to expose the status of a group as a sub-resource you could give it the following URI and implement support for both GET and PUT methods:
/groups/api/groups/{group id}/status
The downside of this approach over PATCH for modification is that you will not be able to make changes to more than one property of a group atomically and transactionally. If transactional changes are important then use PATCH.
If you do decide to expose the status as a sub-resource of a group it should be a link in the representation of the group. For example if the agent gets group 123 and accepts XML the response body could contain:
<group id="123">
<status>Active</status>
<link rel="/linkrels/groups/status" uri="/groups/api/groups/123/status"/>
...
</group>
A hyperlink is needed to fulfill the hypermedia as the engine of application state condition of the REST architectural style.
One possible option to implement such behavior is
PUT /groups/api/v1/groups/{group id}/status
{
"Status":"Activated"
}
And obviously, if someone need to deactivate it, PUT will have Deactivated status in JSON.
In case of necessity of mass activation/deactivation, PATCH can step into the game (not for exact group, but for groups resource:
PATCH /groups/api/v1/groups
{
{ “op”: “replace”, “path”: “/group1/status”, “value”: “Activated” },
{ “op”: “replace”, “path”: “/group7/status”, “value”: “Activated” },
{ “op”: “replace”, “path”: “/group9/status”, “value”: “Deactivated” }
}
In general this is idea as #Andrew Dobrowolski suggesting, but with slight changes in exact realization.
I would generally prefer something a bit simpler, like activate/deactivate sub-resource (linked by a Link header with rel=service).
POST /groups/api/v1/groups/{group id}/activate
or
POST /groups/api/v1/groups/{group id}/deactivate
For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.

How to apply the PUT verb in a REST request?

I'm working on a REST server. I have an order RESOURCE.
From my understanding the PUT verb should create a new order based on the URL. My question is: How can this work if the resource is new and you don't know the ID of the new order?
I know the debate about POST vs PUT, but I'm quoting the w3 specs for PUT http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
"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"
In RESTful APIs, PUT is typically used to update a resource or create one if it doesn't exist at the specified URL (i.e. the client provides the id). If the server generates the id, RESTful APIs typically use a POST to create new resources. In the latter scenario, the generated id/url is usually returned or specified in a redirect.
Example: POST /orders/
According to W3C Both PUT and POST can be used for update and/or create.
The basic difference between them is how the server handles the Request-URI. PUT URI identifies the entity and the server should't try to map it to another URL, while POST URI can be a handler for that content. Examples:
It's OK to POST a new order to /order, but not a PUT. You can update order 1 with a PUT or POST to /order/1.
To put it simply POST is for creating and PUT is for updating. If you don't have an ID for an object because it isn't created yet, you should be using a POST. If an object DOES exist and you just don't have the ID for it, you're going to have to search for it using a GET of some kind.
The thing to remember is Idempotence. A PUT (and GET for that matter) is idempotent. Basically meaning, you can hit the same URL over and over and it shouldn't make a difference the 2nd or 3rd time (It edits the data once, and calling it again it doesn't make that change again). However a POST is not idempotent. Meaning, you hit the same URL 3 or 4 times in a row and it's going to keep changing data (creating more and more objects). This is why a browser will warn you if you click back to a POST url.
You say, "don't know the ID of the new order" therefore the following is not true "URI is capable of being defined as a new resource by the requesting user agent", therefore PUT is not appropriate in your scenario.
Where is the confusion? I am of course assuming the Id would be part of the URL.

Resources