Bootstrap FreeKB - Perl (Scripting) - Getting Started with the LWP::UserAgent REST API module
Perl (Scripting) - Getting Started with the LWP::UserAgent REST API module

Updated:   |  Perl (Scripting) articles

The LWP::UserAgent module can be used to issue a REST API request. For example, let's say a GET request to www.example.com/api should return "Hello World", and Dumper can be used to display the response.

#!/usr/bin/perl
use strict;
use warning;
use LWP::UserAgent;
use Data::Dumper;

my $ua = LWP::UserAgent->new;
my $request = HTTP::Request->new(GET => "http://www.example.com/api");
my $response = $ua->request($request);

print Dumper $response;

 

Something like this should be returned.

$VAR1 = bless( {
                 '_protocol' => 'HTTP/1.1',
                 '_content' => 'Hello World',
                 '_rc' => '200'
});

 

And here is how you would print only the content.

if ( $response->is_success ) {
  print $response->decoded_content;
}
else {
  print "failed";
}

 

Or all headers.

print $response->headers()->as_string;

 

Or a specific header.

print $response->header('Content-Type');

 

Or a previous header, such as when there is a 302 redirect.

print $response->previous->header('location');

 

And here is how you could POST data to www.example.com/api.

#!/usr/bin/perl
use strict;
use warning;
use LWP::UserAgent;
use Data::Dumper;

my $ua = LWP::UserAgent->new;
my $request = $ua->post( "http://www.example.com/api", { 'foo' => 'hello', 'bar' => 'world' );

print Dumper $response;

if ( $response->is_success ) {
  print $response->decoded_content;
}
else {
  print "failed";
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f64eda in the box below so that we can be sure you are a human.