Perl (Scripting) - POST data 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 REST API request. For example, here is how you could POST data foo = hello and bar = world to www.example.com/api.
#!/usr/bin/perl
use strict;
use warning;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $request = $ua->post( "http://www.example.com/api", { 'foo' => 'hello', 'bar' => 'world' } );
if ( $request ->is_success ) {
print $request ->decoded_content;
}
else {
print "failed";
}
Something like this should be returned if the API returns a response.
{
"foo": "Greetings",
"bar": "Human"
}
Better yet, you can store the data being sent to the API in an array.
my @array;
push @array, "foo" => "hello";
push @array, "bar" => "world";
And then use the array in the POST.
my $request = $ua->post( "http://www.example.com/api", \@array );
You may want to use the JSON::Parse module if you want to store a return value in a variable.
my $json = parse_json($request->decoded_content);
print $json->{foo};
Should return.
Greetings
Did you find this article helpful?
If so, consider buying me a coffee over at