For both (create and update) I would use POST since you are changing something in the data store (they are not idempotent function calls). For me this link was very helpful: Form methods
New answer (now that I understand REST better):
PUT is merely a statement of what content the service should, from now on, use to render representations of the resource identified by the client; POST is a statement of what content the service should, from now on, contain (possibly duplicated) but it's up to the server how to identify that content.
PUT x (if x identifies a resource): "Replace the content of the resource identified by x with my content."
PUT x (if x does not identify a resource): "Create a new resource containing my content and use x to identify it."
POST x: "Store my content and give me an identifier that I can use to identify a resource (old or new) containing said content (possibly mixed with other content). Said resource should be identical or subordinate to that which x identifies." "y's resource is subordinate to x's resource" is typically but not necessarily implemented by making y a subpath of x (e.g. x = /foo and y = /foo/bar) and modifying the representation(s) of x's resource to reflect the existence of a new resource, e.g. with a hyperlink to y's resource and some metadata. Only the latter is really essential to good design, as URLs are opaque in REST -- you're supposed to use hypermedia instead of client-side URL construction to traverse the service anyways.
In REST, there's no such thing as a resource containing "content". I refer as "content" to data that the service uses to render representations consistently. It typically consists of some related rows in a database or a file (e.g. an image file). It's up to the service to convert the user's content into something the service can use, e.g. converting a JSON payload into SQL statements.
Original answer (might be easier to read):
PUT /something (if /something already exists): "Take whatever you have at /something and replace it with what I give you."
PUT /something (if /something does not already exist): "Take what I give you and put it at /something."
POST /something: "Take what I give you and put it anywhere you want under /something as long as you give me its URL when you're done."
This is specified in RFC 2616 Â§9.5ff.
POST creates a child resource, so POST to /items creates a resources that lives under the /items resource.
PUT is for creating or replacing something with a known URL.
Therefore PUT is only a candidate for CREATE where you already know the url before the resource is created.
Eg. /blogs/nigel/entry/when_to_use_post_vs_put as the title is used as the resource key
The RFC reads like this:
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. If the server desires that the request be applied to a different URI,
Note: There is a movement towards PATCH for updating existing resources, as PUT specifies that it replaces the whole resource. RFC 5789.
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
GET /user/12345 HTTP/1.1 <-- return that user
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
PUT /user/12345 HTTP/1.1 <--- update the user
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. 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.
Use POST to create, and PUT to update. That's how Rails is doing it, anyway.
PUT /items/1 #=> update
POST /items #=> create
REST is a very high-level concept. In fact, it doesn't even mention HTTP at all!
If you have any doubts about how to implement REST in HTTP, you can always take a look at the Atom Publication Protocol (AtomPub) specification. AtomPub is a standard for writing RESTful webservices with HTTP that was developed by many HTTP and REST luminaries, with some input from Roy Fielding, the inventor of REST and (co-)inventor of HTTP himself.
In fact, you might even be able to use AtomPub directly. While it came out of the blogging community, it is in no way restricted to blogging: it is a generic protocol for RESTfully interacting with arbitrary (nested) collections of arbitrary resources via HTTP. If you can represent your application as a nested collection of resources, then you can just use AtomPub and not worry about whether to use PUT or POST, what HTTP Status Codes to return and all those details.
This is what AtomPub has to say about resource creation:
To add members to a Collection, clients send POST requests to the URI of the Collection.
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.
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.
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.
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.
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.
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 URLs 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.
The most important consideration is reliability. If a POST message gets lost the state of the system is undefined. Automatic recovery is impossible. For PUT messages, the state is undefined only until the first successful retry.
For instance, it may not be a good idea to create credit card transactions with POST.
If you happen to have auto generated URI's on your resource you can still use PUT by passing a generated URI (pointing to an empty resource) to the client.
Some other considerations:
POST invalidates cached copies of the entire containing resource (better consistency)
PUT responses are not cacheable while POST ones are (Require Content-Location and expiration)
PUT is less supported by e.g. Java ME, older browsers, firewalls
Can be performed both with PUT or POST in the following way:
Create a new resource with newResourceId as the identifier, under the /resources URI, or collection.
PUT /resources/<newResourceId> HTTP/1.1
Create 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 right and specific to the left. The generics are usually called collections and the more specific itens can be called resource. Note that a resource can contain a collection.
<-- generic -- specific -->
website.com - whole site
users - collection of users
john - item of the collection, or a resource
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.
Wikipedia - REST
Uniform Resource Identifiers (URI): Generic Syntax and Semantics
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.
If a client wants to transfer hosting responsibility to the server over an HTTP + REST API then the proper method to use is POST. The reason for this is the client does not know the URL of the resource since it is not retaining hosting responsibility and therefore PUT is not an option. There are exceptions to this rule and they occur when the client wishes to retain control over the location structure of the resources it deploys. This is rare and likely means you are doing something else wrong. Your app is not interested in retaining control over resource structure. The app is transferring hosting responsibility, nothing more, so POST is used, not PUT.
At this point some people will argue that if *Restful-URL*s are used, the client does knows the URL of the resource and therefore a PUT is acceptable. After all, this is why canonical, normalized, Ruby on Rails, Django URLs are important, look at the Twitter API â¦ blah blah blah. Those people need to understand there is no such thing as a Restful-URL and that Roy Fielding himself states that:
A REST API must not define fixed resource names or hierarchies (an
obvious coupling of client and server). Servers must have the freedom
to control their own namespace. Instead, allow servers to instruct
clients on how to construct appropriate URIs, such as is done in HTML
forms and URI templates, by defining those instructions within media
types and link relations. [Failure here implies that clients are
assuming a resource structure due to out-of band information, such as
a domain-specific standard, which is the data-oriented equivalent to
RPC's functional coupling].
The idea of a RESTful-URL is actually a violation of REST as the server is in charge of the URL structure and should be free to decide how to use it to avoid coupling. If this confuses you see a future article on the significance of self discovering on API design.
Using POST to create resources comes with a design consideration because POST is not idempotent. This means that repeating a POST several times does not guarantee the same behavior each time. This scares people into using PUT to create resources when they should not. They know it's wrong (POST is for CREATE) but they do it anyway because they don't know how to solve this problem. This concern is demonstrated in the following situation:
The client POST a new resource to the server.
The server processes the request and sends a response.
The client never receives the response.
The server is unaware the client has not received the response.
The client does not have a URL for the resource (therefore PUT is not an option) and repeats the POST.
POST is not idempotent and the server â¦
Step 6 is where people commonly get confused about what to do. However, there is no reason to create a kludge to solve this issue. Instead, HTTP can be used as specified in RFC 2616 and the server replies:
10.4.10 409 Conflict
The request could not be completed due to a conflict with the current
state of the resource. This code is only allowed in situations where
it is expected that the user might be able to resolve the conflict and
resubmit the request. The response body SHOULD include enough
information for the user to recognize the source of the conflict.
Ideally, the response entity would include enough information for the
user or user agent to fix the problem; however, that might not be
possible and is not required.
Conflicts are most likely to occur in response to a PUT request. For
example, if versioning were being used and the entity being PUT
included changes to a resource which conflict with those made by an
earlier (third-party) request, the server might use the 409 response
to indicate that it canât complete the request. In this case, the
response entity would likely contain a list of the differences between
the two versions in a format defined by the response Content-Type.
Replying with a status code of 409 Conflict is the correct recourse because:
Performing a POST of data which has an ID which matches a resource already in the system is âa conflict with the current state of the resource.â
Since the important part is for the client to understand the server has the resource and to take appropriate action. This is a âsituation(s) where it is expected that the user might be able to resolve the conflict and resubmit the request.â
A response which contains the URL of the resource with the conflicting ID and the appropriate preconditions for the resource would provide âenough information for the user or user agent to fix the problemâ which is the ideal case per RFC 2616.
For more information about this read this article.
I'm gonna land with the following:
PUT refers to a resource, identified by the URI. In this case, you are updating it. It is the part of the three verbs referring to resources -- delete and get being the other two.
POST is basically a free form message, with its meaning being defined 'out of band'. If the message can be interpreted as adding a resource to a directory, that would be OK, but basically you need to understand the message you are sending (posting) to know what will happen with the resource.
Because put and get and delete refer to a resource, they are also by definition idempotent.
Post can perform the other three functions, but then the semantics of the request will be lost on the intermediaries such as caches and proxies. This also applies to providing security on the resource, since a post's URI doesn't necessarily indicate the resource it is applying to (it can though).
A put doesn't need to be a create; the service could error if the resource isn't already created but otherwise update it. Or vice versa -- it may create the resource, but not allow updates. The only thing required about PUT is that it points to a specific resource, and its payload is the representation of that resource. A successful put means (barring interference) that a get would retrieve the same 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. 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.
I wrote the following as part of another answer on SO regarding this:
Used to modify and update a resource
POST /questions/<existing_question> HTTP/1.1
Note that the following is an error:
POST /questions/<new_question> HTTP/1.1
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
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
To overwrite an existing resource:
PUT /questions/<existing_question> HTTP/1.1