Sunday, June 28, 2015

REST - PUT Versus POST for RESTful Services

The use of GET and DELETE is pretty obvious for RESTful services, but there's usually some confusion around when to use a PUT versus a POST. The reality is, they can both do the job. But, here's the breakdown on when to use PUT and when to use POST for your REST services.

Use a PUT only when you know the exact URI of the resource that you are creating or updating.

Let's start with creating a new resource. Should you use a PUT or a POST when designing this service? Well, generally speaking, when you are creating a new resource, you probably don't know the exact URI. Why? Because, to retrieve an individual record, we usually provide a REST service that allows clients to specify records by their ID. Example:

# Get customer with ID = 52

GET /customer/52 HTTP/1.1

Host: www.mysite.org


So, if you're creating a new resource, you typically don't know the next ID in the sequence. So, you wouldn't use a PUT in this scenario. Instead, use a POST. Example:

# Request to create a new customer record

POST /customer HTTP/1.1

Host: www.mysite.org

Content-Type: application/xml;charset=UTF-8



<customer>

   <firstname>John</firstname>

   <lastname>Doe</lastname>

</customer>



# Response

HTTP/1.1 201 Created

Location: http://www.mysite.org/customer/52

Content-Location: http://www.mysite.org/customer/52

Content-Type: application/xml;charset=UTF-8


I didn't include the response body, but you get the point. Now that we have the URI for the customer record, we can use a PUT for any future updates.

So, the general rule of thumb:

  • Creating a new resource? Use a POST, unless you already know the URI for the new resource. 
    • The only time you would want to use a PUT for creating a new resource, is when the client applications can specify the exact URI of the new resource that's being created.
  • Updating an existing resource? Use a PUT.
    • However, a POST is a viable option as well. Really, anywhere you can use a PUT, you can use a POST. But, if already know the URI of the resource that you're modifying, a PUT is preferred.

No comments:

Post a Comment