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

POST Request

For the most part, HTTP POST requests are used to update existing resources on a server. You will be making a request to a service and passing along a POST payload, which the server then uses to denote the update resource or hold the content to be updated.

In PHP, we can use cURL to issue a POST request:

<?php
$url = 'http://www.example.com/request.php';
$postvals = 'firstName=John&lastName=Smith';

$ch = curl_init($url);
$options = array(
   CURLOPT_CUSTOMREQUEST => 'POST',
   CURLOPT_URL => $url,
   CURLOPT_POST => 1,
   CURLOPT_POSTFIELDS => $postvals,
   CURLOPT_RETURNTRANSFER => 1
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
curl_close($ch);
?>

As with the GET request, we are making the call to a specified URL, but this time we are creating a POST string that we will send. In addition to the cURL options from the GET request, we use CURLOPT_CUSTOMREQUEST and CURLOPT_POST to state that we want to make a POST request and CURLOPT_POSTFIELDS to attach the data to send in the POST.

In Python, we can once again use urllib for the POST request:

import urllib

url = 'http://www.example.com/request.py'
postvals = {'first_name': 'John', 'last_name': 'Smith'}

params = urllib.urlencode(postvals)
f = urllib.urlopen(url, params)
response = f.read()

As with the GET request, we are making the request to a specific URL. This time, though, we create the object that we want to POST, encode it, and pass it along when we call urlopen(...).

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