12.4. Using REST in Perl

To work with HTTP in Perl, we will use LWP -- the Library for WWW in Perl.

Issuing GET Requests
GET requests are pretty trivial with LWP, especially if you don't care much about setting headers in the request or reading headers in the response:

use LWP::Simple;

my $url = 'http://www.acme.com/products/3322';
          # ACME boomerang
my $response = get $url;
die 'Error getting $url' unless defined $response;

For more advanced features, you'll need to create a browser object, thus:

use LWP;
my $browser = LWP::UserAgent->new;
my $url = 'http://www.acme.com/products/3322';

# Issue request, with an HTTP header
my $response = $browser->get($url,
  'User-Agent' => 'Mozilla/4.0 (compatible; MSIE 7.0)',
);
die 'Error getting $url' unless $response->is_success;
print 'Content type is ', $response->content_type;
print 'Content is:';
print $response->content;

Issuing POST Requests
The same browser object defined above can be used to issue POST requests, too. Field names are directly mapped to values, thus:

my $response = $browser->post($url,
  [
   'firstName' => 'John',
   'lastName' => 'Doe'
  ],
);
die 'Error getting $url' unless $response->is_success;

Note that the UserAgent class allows you to easily set and read cookies, too, but these should be avoided in REST designs.

Additional information about using LWP for web requests can be found in the article Web Basics with LWP, by Sean M. Burke, author of Perl & LWP.

3 comments:

Chris Hamel said...

For the LWP challenged, the following modifications enabled this to work using supplied credentials:

my $browser = LWP::UserAgent->new(keep_alive=>1);
$browser->env_proxy;
$browser->credentials('www.acme.com:80','','scott'=>'tiger');

Unknown said...

For the post, the parameters need '=>' and not just the '='

my $response = $browser->post($url,
[
'firstName' => 'John',
'lastName' => 'Doe'
],
);
die 'Error getting $url' unless $response->is_success;

Dr. M. Elkstein said...

Thanks Paul! I've corrected the page.