Sunday, March 23, 2014

REST: POST vs PUT for Resource Creation

Questions often come up about whether to use PUT or POST for creating resources in REST APIs.

I've found both are appropriate in different situations.


PUT is best used when the client is providing the resource id.
PUT https://.../v1/resource/<id>
Per spec PUT is for storing the enclosed entity "under the supplied Request-URI".  This makes it the ideal HTTP method for use when creating or "storing" a resource.  Only when all the requirements for PUT can't be met should POST be considered.   The perfect example of when the client cannot provide the resource id.


POST is best used when the client doesn't know the resource id a priori.
POST https://.../v1/resource
POST shouldn't be the first choice for resource creation is because  it's really more of a catchall method.
"The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI."
It doesn't require anything be created, or made available for later.
"A successful POST does not require that the entity be created as a resource on the origin server or made accessible for future reference. That is, the action performed by the POST method might not result in a resource that can be identified by a URI."

No comments:

Post a Comment