O'Reilly logo

Programming Social Applications by Jonathan LeBlanc

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

PUT Request

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 CURLOPT_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', ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required