Bootstrap FreeKB - Perl (Scripting) - POST data with the LWP::UserAgent REST API module
Perl (Scripting) - POST data 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, 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 Buy Me A Coffee



Comments


Add a Comment


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