- Trophy Points
- Mar 17, 2022
The difference between POST and PUT according to RFCAccording to RFC 2616, § 9.5,
POSTis used to create a resource:
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.
According to RFC 2616, § 9.6,
PUTis used to create or replace a resource:
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.
Let's find out which HTTP method should be used to create a resource.
Or should both be supported?
Overall, both can be used to create a resource. You need to ask, "what are you performing the action upon?", to distinguish what you should be using. Let's say you're developing 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.
POST means "create new" as in "Here is the input for creating a user, create it for me".
POST creates a child resource, so POST to
/questionscreates a resource that lives under the
/questions/1. Sending the same post packet twice will create two resources.
PUT means "insert, replace if already exists" as in "Here is the data for user 5".
PUT is for creating or replacing a resource at a URL known by the client. Therefore, PUT is only a candidate for CREATE, where the client already knows the URL before creating the resource. E.g.
/questions/50350. The question ID (30350) is used as the resource key.
- PUT is defined to assume idempotency, it replaces the resource with a known URL, if it already exists, so if you send a PUT request twice, it should have no additional effect. Just make sure that the PUT idempotence is actually implemented correctly on the server.
- Sending a POST request twice with the same data means creating two identical resources with different ids.
- PUT has mostly been used to update resources (by replacing them in their entireties).
- Do you name the URL objects you create explicitly or do you allow the server to decide? If you name them, use PUT. If you allow the server to decide, use POST.
SummaryGeneral rule: if you know the ID or name of the item, use PUT. If you want the item ID or name to be assigned by the receiving party, use POST.
- POST to a URL creates a child resource at a server-defined URL.
- PUT to a URL creates/replaces the resource in its entirety at the client-defined URL.
- PATCH to a URL updates part of the resource at that client-defined URL.