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', ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access