http - services - rest put example
PUT vs. POST in REST (20)
According to the HTTP/1.1 Spec:
POSTmethod is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the
In other words,
POST is used to create.
PUTmethod requests that the enclosed entity be stored under the supplied
Request-URI. If the
Request-URIrefers 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-URIdoes 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."
PUT is used to create or update.
So, which one should be used to create a resource? Or one needs to support both?
the origin server can create the resource with that URI
So you use POST and probably, but not necessary PUT for resource creation. You don't have to support both. For me POST is perfectly enough. So it is a design decision.
As your quote mentioned, you use PUT for creation of there is no resource assigned to an IRI, and you want to create a resource anyway. For example,
PUT /users/123/password usually replaces the old password with a new one, but you can use it to create a password if it does not exist already (for example, by freshly registered users or by restoring banned users).
Can be performed with both PUT or POST in the following way:
Creates THE new resource with newResourceId as the identifier, under the /resources URI, or collection.
PUT /resources/<newResourceId> HTTP/1.1
Creates A new resource under the /resources URI, or collection. Usually the identifier is returned by the server.
POST /resources HTTP/1.1
Can only be performed with PUT in the following way:
Updates the resource with existingResourceId as the identifier, under the /resources URI, or collection.
PUT /resources/<existingResourceId> HTTP/1.1
When dealing with REST and URI as general, you have generic on the left and specific on the right. The generics are usually called collections and the more specific items can be called resource. Note that a resource can contain a collection.
<-- generic -- specific -->
URI: website.com/users/john website.com - whole site users - collection of users john - item of the collection, or a resource URI:website.com/users/john/posts/23 website.com - whole site users - collection of users john - item of the collection, or a resource posts - collection of posts from john 23 - post from john with identifier 23, also a resource
When you use POST you are always refering to a collection, so whenever you say:
POST /users HTTP/1.1
you are posting a new user to the users collection.
If you go on and try something like this:
POST /users/john HTTP/1.1
it will work, but semantically you are saying that you want to add a resource to the john collection under the users collection.
Once you are using PUT you are refering to a resource or single item, possibly inside a collection. So when you say:
PUT /users/john HTTP/1.1
you are telling to the server update, or create if it doesn't exist, the john resource under the users collection.
Let me highlight some important parts of the spec:
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line
Hence, creates a new resource on a collection.
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."
Hence, create or update based on existence of the resource.
Both PUT and POST can be used for creating.
You have to ask "what are you performing the action to?" to distinguish what you should be using. Let's assume you're designing an API for asking questions. If you want to use POST then you would do that to a list of questions. If you want to use PUT then you would do that to a particular question.
Great both can be used, so which one should I use in my RESTful design:
You do not need to support both PUT and POST.
Which is used is left up to you. But just remember to use the right one depending on what object you are referencing in the request.
- Do you name your URL objects you create explicitly, or let the server decide? If you name them then use PUT. If you let the server decide then use POST.
- PUT is idempotent, so if you PUT an object twice, it has no effect. This is a nice property, so I would use PUT when possible.
- You can update or create a resource with PUT with the same object URL
- With POST you can have 2 requests coming in at the same time making modifications to a URL, and they may update different parts of the object.
Used to modify and update a resource
POST /questions/<existing_question> HTTP/1.1 Host: www.example.com/
Note that the following is an error:
POST /questions/<new_question> HTTP/1.1 Host: www.example.com/
If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a 'resource not found' error because
<new_question>does not exist yet. You should PUT the
<new_question>resource on the server first.
You could though do something like this to create a resources using POST:
POST /questions HTTP/1.1 Host: www.example.com/
Note that in this case the resource name is not specified, the new objects URL path would be returned to you.
Used to create a resource, or overwrite it. While you specify the resources new URL.
For a new resource:
PUT /questions/<new_question> HTTP/1.1 Host: www.example.com/
To overwrite an existing resource:
PUT /questions/<existing_question> HTTP/1.1 Host: www.example.com/
Simple rule of thumb: Use POST to create, use PUT to update.
- POST is used to send data to server.
- Useful when the resource's URL is unknown
- PUT is used to transfer state to the server
- Useful when a resource's URL is known
To understand it we need to question why PUT was required, what were the problems PUT was trying to solve that POST couldn't.
From a REST architecture's point of view there is none that matters. We could have lived without PUT as well. But from a client developer's point of view it made his/her life a lot simpler.
Prior to PUT, clients couldn't directly know the URL that the server generated or if all it had generated any or whether the data to be sent to the server is already updated or not. PUT relieved the developer of all these headaches. PUT is idempotent, PUT handles race conditions, and PUT lets the client choose the URL.
At the risk of restating what has already been said, it seems important to remember that PUT implies that the client controls what the URL is going to end up being, when creating a resource. So part of the choice between PUT and POST is going to be about how much you can trust the client to provide correct, normalized URL that are coherent with whatever your URL scheme is.
When you can't fully trust the client to do the right thing, it would be more appropriate to use POST to create a new item and then send the URL back to the client in the response.
I like this advice, from RFC 2616's definition of PUT:
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource.
This jibes with the other advice here, that PUT is best applied to resources that already have a name, and POST is good for creating a new object under an existing resource (and letting the server name it).
I interpret this, and the idempotency requirements on PUT, to mean that:
- POST is good for creating new objects under a collection (and create does not need to be idempotent)
- PUT is good for updating existing objects (and update needs to be idempotent)
- POST can also be used for non-idempotent updates to existing objects (especially, changing part of an object without specifying the whole thing -- if you think about it, creating a new member of a collection is actually a special case of this kind of update, from the collection's perspective)
- PUT can also be used for create if and only if you allow the client to name the resource. But since REST clients aren't supposed to make assumptions about URL structure, this is less in the intended spirit of things.
I'd like to add my "pragmatic" advice. Use PUT when you know the "id" by which the object you are saving can be retrieved. Using PUT won't work too well if you need, say, a database generated id to be returned for you to do future lookups or updates.
So: To save an existing user, or one where the client generates the id and it's been verified that the id is unique:
PUT /user/12345 HTTP/1.1 <-- create the user providing the id 12345 Host: mydomain.com GET /user/12345 HTTP/1.1 <-- return that user Host: mydomain.com
Otherwise, use POST to initially create the object, and PUT to update the object:
POST /user HTTP/1.1 <--- create the user, server returns 12345 Host: mydomain.com PUT /user/12345 HTTP/1.1 <--- update the user Host: mydomain.com
If you are familiar with database operations, there are
- Merge (Update if already existing, else insert)
PUT for Merge and update like operations and use
POST for Insertions.
In a very simple way I'm taking the example of the Facebook timeline.
Case 1: When you post something on your timeline, it's a fresh new entry. So in this case they use the POST method because the POST method is non-idempotent.
Case 2: If your friend comment on your post the first time, that also will create a new entry in the database so the POST method used.
Case 3: If your friend edits his comment, in this case, they had a comment id, so they will update an existing comment instead of creating a new entry in the database. Therefore for this type of operation use the PUT method because it is idempotent.*
In a single line, use POST to add a new entry in the database and PUT to update something in the database.
In practice, POST works well for creating resources. The URL of the newly created resource should be returned in the Location response header. PUT should be used for updating a resource completely. Please understand that these are the best practices when designing a RESTful API. HTTP specification as such does not restrict using PUT/POST with a few restrictions for creating/updating resources. Take a look at http://techoctave.com/c7/posts/71-twitter-rest-api-dissected that summarizes the best practices.
PUT is idempotent, where the resource state will be the same if the same operation is executed one time or multiple times.
POST is non-idempotent, where the resource state may become different if the operation is executed multiple times as compared to executing a single time.
Analogy with database query
PUT You can think of similar to "UPDATE STUDENT SET address = "abc" where id="123";
POST You can think of something like "INSERT INTO STUDENT(name, address) VALUES ("abc", "xyzzz");
Student Id is auto generated.
With PUT, if the same query is executed multiple times or one time, the STUDENT table state remains the same.
In case of POST, if the same query is executed multiple times then multiple Student records get created in the database and the database state changes on each execution of an "INSERT" query.
NOTE: PUT needs a resource location (already-resource) on which update needs to happen, whereas POST doesn't require that. Therefore intuitively POST is meant for creation of a new resource, whereas PUT is needed for updating the already existing resource.
Some may come up with that updates can be performed with POST. There is no hard rule which one to use for updates or which one to use for create. Again these are conventions, and intuitively I'm inclined with the above mentioned reasoning and follow it.
POST is like posting a letter to a mailbox or posting an email to an email queue. PUT is like when you put an object in a cubby hole or a place on a shelf (it has a known address).
With POST, you're posting to the address of the QUEUE or COLLECTION. With PUT, you're putting to the address of the ITEM.
PUT is idempotent. You can send the request 100 times and it will not matter. POST is not idempotent. If you send the request 100 times, you'll get 100 emails or 100 letters in your postal box.
A general rule: if you know the id or name of the item, use PUT. If you want the id or name of the item to be assigned by the receiving party, use POST.
POST means "create new" as in "Here is the input for creating a user, create it for me".
PUT means "insert, replace if already exists" as in "Here is the data for user 5".
You POST to example.com/users since you don't know the URL of the user yet, you want the server to create it.
You PUT to example.com/users/id since you want to replace/create a specific user.
POSTing twice with the same data means create two identical users with different ids. PUTing twice with the same data creates the user the first and updates him to the same state the second time (no changes). Since you end up with the same state after a PUT no matter how many times you perform it, it is said to be "equally potent" every time - idempotent. This is useful for automatically retrying requests. No more 'are you sure you want to resend' when you push the back button on the browser.
A general advice is to use POST when you need the server to be in control of URL generation of your resources. Use PUT otherwise. Prefer PUT over POST.
Readers new to this topic will be struck by the endless discussion about what you should do, and the relative absence of lessons from experience. The fact that REST is "preferred" over SOAP is, I suppose, a high-level learning from experience, but goodness we must have progressed from there? It's 2016. Roy's dissertation was in 2000. What have we developed? Was it fun? Was it easy to integrate with? To support? Will it handle the rise of smartphones and flaky mobile connections?
According to ME, real-life networks are unreliable. Requests timeout. Connections are reset. Networks go down for hours or days at a time. Trains go into tunnels with mobile users aboard. For any given request (as occasionally acknowledged in all this discussion) the request can fall in the water on its way, or the response can fall in the water on its way back. In these conditions, issuing PUT, POST and DELETE requests directly against substantive resources has always struck me as a little brutal and naive.
HTTP does nothing to ensure reliable completion of the request-response, and that's just fine because this is properly the job of network-aware applications. Developing such an application, you can jump through hoops to use PUT instead of POST, then more hoops to give a certain kind of error on the server if you detect duplicate requests. Back at the client, you then have to jump through hoops to interpret these errors, refetch, revalidate and repost.
Or you can do this: consider your unsafe requests as ephemeral single-user resources (let's call them actions). Clients request a new "action" on a substantive resource with an empty POST to the resource. POST will be used only for this. Once safely in possession of the URI of the freshly minted action, the client PUTs the unsafe request to the action URI, not the target resource. Resolving the action and updating the "real" resource is properly the job of your API, and is here decoupled from the unreliable network.
The server does the business, returns the response and stores it against the agreed action URI. If anything goes wrong, the client repeats the request (natural behaviour!), and if the server has already seen it, it repeats the stored response and does nothing else.
You will quickly spot the similarity with promises: we create and return the placeholder for the result before doing anything. Also like a promise, an action can succeed or fail one time, but its result can be fetched repeatedly.
Best of all, we give sending and receiving applications a chance to link the uniquely identified action to uniqueness in their respective environments. And we can start to demand, and enforce!, responsible behaviour from clients: repeat your requests as much as you like, but don't go generating a new action until you're in possession of a definitive result from the existing one.
As such, numerous thorny problems go away. Repeated insert requests won't create duplicates, and we don't create the real resource until we're in possession of the data. (database columns can stay not-nullable). Repeated update requests won't hit incompatible states and won't overwrite subsequent changes. Clients can (re)fetch and seamlessy process the original confirmation for whatever reason (client crashed, response went missing, etc.).
Successive delete requests can see and process the original confirmation, without hitting a 404 error. If things take longer than expected, we can respond provisionally, and we have a place where the client can check back for the definitive result. The nicest part of this pattern is its Kung-Fu (Panda) property. We take a weakness, the propensity for clients to repeat a request any time they don't understand the response, and turn it into a strength :-)
Before telling me this is not RESTful, please consider the numerous ways in which REST principles are respected. Clients don't construct URLs. The API stays discoverable, albeit with a little change in semantics. HTTP verbs are used appropriately. If you think this is a huge change to implement, I can tell you from experience that it's not.
If you think you'll have huge amounts of data to store, let's talk volumes: a typical update confirmation is a fraction of a kilobyte. HTTP currently gives you a minute or two to respond definitively. Even if you only store actions for a week, clients have ample chance to catch up. If you have very high volumes, you may want a dedicated acid-compliant key value store, or an in-memory solution.
Ruby on Rails 4.0 will use the 'PATCH' method instead of PUT to do partial updates.
RFC 5789 says about PATCH (since 1995):
A new method is necessary to improve interoperability and prevent errors. The PUT method is already defined to overwrite a resource with a complete new body, and cannot be reused to do partial changes. Otherwise, proxies and caches, and even clients and servers, may get confused as to the result of the operation. POST is already used but without broad interoperability (for one, there is no standard way to discover patch format support). PATCH was mentioned in earlier HTTP specifications, but not completely defined.
"Edge Rails: PATCH is the new primary HTTP method for updates" explains it.
The semantics are supposed be different, in that "PUT", like "GET" is supposed to be idempotent -- meaning, you can the same exact PUT request multiple times and the result will be as if you executed it only once.
I will describe the conventions which I think are most widely used and are most useful:
When you PUT a resource at a particular URL what happens is that it should get saved at that URL, or something along those lines.
When you POST to a resource at a particular URL, often you are posting a related piece of information to that URL. This implies that the resource at the URL already exists.
For example, when you want to create a new stream, you can PUT it to some URL. But when you want to POST a message to an existing stream, you POST to its URL.
As for modifying the properties of the stream, you can do that with either PUT or POST. Basically, only use "PUT" when the operation is idempotent - otherwise use POST.
Note, however, that not all modern browsers support HTTP verbs other than GET or POST.
There seems to always be some confusion as to when to use the HTTP POST versus the HTTP PUT method for REST services. Most developers will try to associate CRUD operations directly to HTTP methods. I will argue that this is not correct and one can not simply associate the CRUD concepts to the HTTP methods. That is:
Create => HTTP PUT Retrieve => HTTP GET Update => HTTP POST Delete => HTTP DELETE
It is true that the R(etrieve) and D(elete) of the CRUD operations can be mapped directly to the HTTP methods GET and DELETE respectively. However, the confusion lies in the C(reate) and U(update) operations. In some cases, one can use the PUT for a create while in other cases a POST will be required. The ambiguity lies in the definition of an HTTP PUT method versus an HTTP POST method.
According to the HTTP 1.1 specifications the GET, HEAD, DELETE, and PUT methods must be idempotent, and the POST method is not idempotent. That is to say that an operation is idempotent if it can be performed on a resource once or many times and always return the same state of that resource. Whereas a non idempotent operation can return a modified state of the resource from one request to another. Hence, in a non idempotent operation, there is no guarantee that one will receive the same state of a resource.
Based on the above idempotent definition, my take on using the HTTP PUT method versus using the HTTP POST method for REST services is: Use the HTTP PUT method when:
The client includes all aspect of the resource including the unique identifier to uniquely identify the resource. Example: creating a new employee. The client provides all the information for a resource to be able to modify that resource.This implies that the server side does not update any aspect of the resource (such as an update date).
In both cases, these operations can be performed multiple times with the same results. That is the resource will not be changed by requesting the operation more than once. Hence, a true idempotent operation. Use the HTTP POST method when:
The server will provide some information concerning the newly created resource. For example, take a logging system. A new entry in the log will most likely have a numbering scheme which is determined on the server side. Upon creating a new log entry, the new sequence number will be determined by the server and not by the client. On a modification of a resource, the server will provide such information as a resource state or an update date. Again in this case not all information was provided by the client and the resource will be changing from one modification request to the next. Hence a non idempotent operation.
Do not directly correlate and map CRUD operations to HTTP methods for REST services. The use of an HTTP PUT method versus an HTTP POST method should be based on the idempotent aspect of that operation. That is, if the operation is idempotent, then use the HTTP PUT method. If the operation is non idempotent, then use the HTTP POST method.
While there is probably an agnostic way to describe these, it does seem to be conflicting with various statements from answers to websites.
Let's be very clear and direct here. If you are a .NET developer working with Web API, the facts are (from the Microsoft API documentation), http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations:
1. PUT = UPDATE (/api/products/id) 2. MCSD Exams 2014 - UPDATE = PUT, there are **NO** multiple answers for that question period.
Sure you "can" use "POST" to update, but just follow the conventions laid out for you with your given framework. In my case it is .NET / Web API, so PUT is for UPDATE there is no debate.
I hope this helps any Microsoft developers that read all comments with Amazon and Sun/Java website links.
You can find assertions on the web that say
- POST should be used to create a resource, and PUT should be used to modify one
- PUT should be used to create a resource, and POST should be used to modify one
Neither is quite right.
Better is to choose between PUT and POST based on idempotence of the action.
PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same.
x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!
POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that
x++ is not idempotent.
By this argument, PUT is for creating when you know the URL of the thing you will create. POST can be used to create when you know the URL of the "factory" or manager for the category of things you want to create.