Perl (Scripting) - headers with the LWP::UserAgent REST API module

by
Jeremy Canfield |
Updated: February 28 2023
| Perl (Scripting) articles
The LWP::UserAgent module can be used to issue a request to a REST API. This is handled differently in a GET request vs. a POST request.
GET request
Let's say a GET request to www.example.com/api should return "Hello World".
The $request->header option can be used to include headers.
#!/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");
$request->header( "Accept" => "application/json" );
my $response = $ua->request($request);
print Dumper $response;
Dumper can be used to display the 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 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');
POST request
And here is how you would include the Accept => application/json header in a POST request.
#!/usr/bin/perl
use strict;
use warning;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $request = $ua->post( "http://www.example.com/api", "Accept" => "application/json", \@array );
if ( $request->is_success ) {
print $request->decoded_content;
}
else {
print "failed";
}
Did you find this article helpful?
If so, consider buying me a coffee over at