Priya Chatterjee
Priya Chatterjee

Reputation: 11

Perl - API Post

This is the first time I am trying to use Perl for Post API. Below is the code I have written.

use REST::Client;
use MIME::Base64;

my $username = 'user';
my $password = 'passwrd';

my $request_url =  'https:hereismyurl';
my $headers = {
   Authorization => 'Basic ' . encode_base64($username . ':' . $password),
   OSvC-CREST-Application-Context => 'Test',
   Content-type => 'application/json'
};    
my $body_content='{"id" :106197,"filters":[{"name": "Date Range","values":["2021-09-27T00:00:00.000Z","2021-09-28T00:00:00.000Z"]}]}';    
my $client = REST::Client->new();
$client->POST($request_url, [$body_content, %$headers]);
print $client->responseContent();

But I get the below error.

Not a SCALAR reference at /usr/share/perl5/LWP/Protocol/http.pm line 203.

Please can someone help me as to where I’m going wrong, many thanks in advance!

Upvotes: 1

Views: 197

Answers (1)

Dada
Dada

Reputation: 6626

You should do

$client->POST($request_url, $body_content, $headers);

instead of

$client->POST($request_url, [$body_content, %$headers]);

The [$body_content, %$headers] in the documation mean that those 2 parameters are optional, and that $headers should be a hash reference.

Moreover, you should quote OSvC-CREST-Application-Context and Content-type:

my $headers = {
   Authorization => 'Basic ' . encode_base64($username . ':' . $password),
   'OSvC-CREST-Application-Context' => 'Test',
   'Content-type' => 'application/json'
};   

Otherwise, Perl thinks that Content and type are two strings representing numbers that you are trying to subtract, and interprets them as 0 and 0. You thus get 0 => 'Test', 0 => 'application/json' in your hash (and only the latter remains).
To catch this kind of mistakes, always add use strict and use warnings at the beginning of your scripts. Here, this would have produced the following errors:

Bareword "OSvC" not allowed while "strict subs" in use at t3.pl line 11.
Bareword "CREST" not allowed while "strict subs" in use at t3.pl line 11.
Bareword "Application" not allowed while "strict subs" in use at t3.pl line 11.
Bareword "Content" not allowed while "strict subs" in use at t3.pl line 11.

Upvotes: 4

Related Questions