Perl (Scripting) - basic authentication username password 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 curl request and return the response. If basic authentication is needed for the URL being requested, authorization_basic can be used.
For example, let's say a 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");
$request->authorization_basic( "john.doe", "itsasecret" );
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.
print $response->decoded_content;
Did you find this article helpful?
If so, consider buying me a coffee over at