Reputation: 165
I'm having some trouble understanding the proper way to set headers for HTTP::Tiny
in Perl 5. So far I have seen examples of hashes, hash references, and a myriad of other seemingly incomposable ways.
What is the proper way of setting the headers for a request? What's an easy way to view the request before it is sent?
Here is some example code:
#!/usr/bin/env perl
use 5.12.1;
use HTTP::Tiny;
my $api_key = "::";
my %headers = (Authorization => sprintf 'Bearer %s', $api_key);
my $url = "https://api-fxpractice.oanda.com/v3/accounts";
my $response = HTTP::Tiny->new($url,
default_headers => {'Content-Type' => 'application/json'});
my $response = HTTP::Tiny->new->get($url, { default_headers => \%headers } );
print "$response->{status} $response->{reason}\n";
while ( my ( $k, $v ) = each %{ $response->{headers} } ) {
print "$k: $_\n";
}
}
print $response->{content} if length $response->{content};
And it is giving me a 401.
Thank you!
Upvotes: 1
Views: 4959
Reputation: 101
hash means just %hash=(key=>value)
hash references means just $hashref={key=>value}
and this equal to $hashref=\%hash;
So
$http = HTTP::Tiny->new( %attributes )
is just
$http = HTTP::Tiny->new( attr1=>value1, ... )
And
$response = $http->get($url, \%options)
is
$response = $http->get($url, {attr1=>value1, ...} )
illustrative examples:
use HTTP::Tiny;
HTTP::Tiny->new->get($url);
HTTP::Tiny->new->get($url, { headers => { header1=>value1, header2=>value2 } };
# with headers set in one place
$handle=HTTP::Tiny->new( default_headers=>{h1=>3, h2=>4} );
$handle->get($url);
$handle->get($url, headers=>{ h2=>'overwrite' });
# without shorthand
HTTP::Tiny->new->request('GET', $url);
HTTP::Tiny->new->request('GET',$url, { headers => { header1=>value1, header2=>value2 } };
# post
HTTP::Tiny->new->request('POST',$url, { headers => { header1=>value1, header2=>value2 }, content=>'body to post' };
Upvotes: 1
Reputation: 165
Turns out the problem had a lot to do with me being stupid and not paying attention to the details. Basically,
`
my $api_key = "::"
my %headers = (
"Content-Type" => "application/json",
"Authorization" => sprintf 'Bearer %s', $api_key);
my $url = "https://api-fxpractice.oanda.com/v1/accounts";
my $response = HTTP::Tiny->new->get($url, { headers => \%headers } );
print "$response->{status} $response->{reason}\n";
while ( my ( $k, $v ) = each %{ $response->{headers} } ) {
for ( ref $v eq 'ARRAY' ? @$v : $v ) {
print "$k: $_\n";
}
}
print $response->{content} if length $response->{content};
`
Upvotes: 0