0

I have a hash $customs which looks like:

{
   'custom1': 'a',
   'custom2': 'b',
   ...
}

I'm trying to pass it the a REST API. The data should look like:

{
    'data': {
        'customs': {
            'custom1': 'a',
            'custom2': 'b',
            ...
        }
    }
}

The code:

my @data = [{ 'customs' => \%customs }];
my $request = PUT($url,@data);

But in my REST API I see that the data is:

{'customs': ['HASH(0x1e47648)']}

How should I pass it right?

vesii
  • 2,760
  • 4
  • 25
  • 71

2 Answers2

3

HTTP::Request::Common is a low-level HTTP library. PUT's arguments are keys and values for a form request. Instead, you want to send some arbitrary data as JSON.

PUT will not do this for you. You need to do the JSON encoding, pass that as the content of the request, and set the content type.

require JSON;

my $data = { data => { customs => \%customs } };

my $request = PUT(
  $url,
  Content_Type => 'application/json'
  Content => JSON->new->utf8->encode($data)
);
Schwern
  • 153,029
  • 25
  • 195
  • 336
1

You might also consider something a bit more friendly, such as Mojo::UserAgent. It handles many of the details for you:

use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;

my $data = { data => { customs => \%customs } };

my $tx = $ua->post( $url, json => $data )

I have another example in a different answer.

brian d foy
  • 129,424
  • 31
  • 207
  • 592