Even though there are many web services that support only a subset of the RESTful architecture—GET and POST requests—fully RESTful services include PUT and DELETE requests as well.
PUT requests are a method for inserting new resources into a service. This request type is very similar to a POST request in technical implementation, and the two requests are often confused with each other.
In PHP, we will once again use a cURL request with some options set:
<?php $url = 'http://www.example.com/request.php'; $postvals = 'firstName=John&lastName=Smith'; $ch = curl_init($url); $options = array( CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_URL => $url, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $postvals, CURLOPT_HTTPHEADER => array('Content-Length: ' . strlen($postvals)), CURLOPT_RETURNTRANSFER => 1 ); curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch); ?>
This request mimics that of the POST
request, except that we set a different CURL
OPT_CUSTOMREQUEST
value (PUT
). In this example, we can also set an HTTP
header with the content length of the POSTed fields if
required.
In Python, this request is a little trickier because there are a
few quirks to making requests with urllib2
:
import urllib import urllib2 url = 'http://www.example.com/request.py' postvals = {'first_name': 'John', 'last_name': 'Smith'} params = urllib.urlencode(postvals) opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request(url, data=params) request.add_header('Content-Type', 'application/json') request.get_method = lambda: 'PUT' f = opener.open(request) response = f.read()
The following code in the urllib2
standard library helps us determine
which HTTP method to use in a request:
def get_method(self): if self.has_data(): return 'POST' else: return 'GET'
As you can see, it doesn’t exactly support any types other than
GET and POST, so we need to make a few adjustments. We first generate
our URL that will be called, and then build and encode the parameters to
send with the PUT request. We then create our HTTP handler opener and
generate the request to our URL with the parameter object through the
urllib2.Request(...)
request. Then,
we add a Content-Type
header for the
request. Now we need to override the method that urllib2
will use in the request by manually
setting the get_method
to PUT
. Finally, we open the URL location from
the request
object and read back the
response.
18.119.162.49