Search code examples
perlhttppostlwp

how to pass variable to http post API in Perl?


My snippet as below, I googled and cannot find a solution to pass variable to the post request in my quoted string. Most of the google result are just pass plain Json key value string pairs to the post content. But I need to pass the parameter to the inner Json value part and call the related REST api. any suggestions? Thanks!

#!/usr/bin/perl -w
use strict;
use warnings;

# Create a user agent object
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1");


# Create a request
my $req = HTTP::Request->new(POST => 'https://oapi.dingtalk.com/robot/send?access_token=foofb73f');

$req->content_type('application/json');

my $var1="value from var";

# works fine
my $message = '{"msgtype": "text","text":{"content":"plain string ok"}}';

# failed to compile
# my $message = '{"msgtype": "text","text":{"content":$var1}}';


$req->content($message);

# Pass request to the user agent and get a response back
my $res = $ua->request($req);

# Check the outcome of the response
if ($res->is_success) {
  print $res->content;
} else {
  print $res->status_line, "n";
}

Solution

  • You didn't properly convert the value into a JSON string.

    use Cpanel::JSON::XS qw( encode_json );
    
    my $message = encode_json({ msgtype => "text", text => { content => $var1 } });