cormanaz has asked for the wisdom of the Perl Monks concerning the following question:

Greetings. I am trying to use the bit.ly api to expand some shortened links. I have an access token. Their docs say you provide this in the POST header like so Authorization: Bearer {token}. But HTTP::Reqest expects the header values to be defined as key/value pairs. So the question is, how do I configure the key/value pairs? This does not work:
use LWP::UserAgent; use JSON::XS; my $browser = LWP::UserAgent->new(timeout => 30); my $url = 'https://api-ssl.bitly.com/v4/expand'; my $header = ['Authorization' => '1a2b3c4d5e']; # not my real access t +oken my $data = {"bitlink_id" => 'ze6poY'}; my $encoded_data = encode_json($data); my $r = HTTP::Request->new('POST', $url, $header, $encoded_data); my $response = $browser->request($r); my $foo = 1; if ($response->is_success) { print $response->decoded_content; } else { die $response->status_line; }
Neither does $header = ['Authorization' => 'Bearer 1a2b3c4d']; or $header = ['Authorization' => 'Bearer {1a2b3c4d}'];

Replies are listed 'Best First'.
Re: How to format HTTP::Request for bit.ly api expand endpoint
by Corion (Patriarch) on May 22, 2020 at 17:23 UTC

    It should be

    my $header = [ 'Authorization' => 'Bearer 1a2b3c4d5e' ];

    If that doesn't work, print your HTTP::Request->headers->as_string and look at where this differs from the documentation.

      Right you are, Corion. Here is working code, in case anyone else is trying to do this. The other tricky thing was how to pass the short URL: Not the hash, and not the whole URL, but the domain plus the hash. I can't imagine why that do it that way instead of just using the hash. It's not like they're going to be lengthening non-bitly URLs :-/
      use LWP::UserAgent; use JSON::XS; our $browser = LWP::UserAgent->new(timeout => 30); my $url = 'https://api-ssl.bitly.com/v4/expand'; my $header = ['Authorization' => 'Bearer 1a2b3c4d5e']; # use a valid o +ne instead of this made-up one my $data = {"bitlink_id" => 'bit.ly/361RdUL'}; # note domain is includ +ed my $encoded_data = encode_json($data); my $r = HTTP::Request->new('POST', $url, $header, $encoded_data); my $response = $browser->request($r); my $foo = 1; if ($response->is_success) { print $response->decoded_content; } else { die $response->status_line; }
        I don't know if Bearer is case sensitive, but I am mentioning this because I've seen this be mentioned as a gotcha in other APIs before.

        Also, The OAuth 2.0 Authorization Framework: Bearer Token Usage (rfc6750) does mention this:

        >Unless otherwise noted, all the protocol parameter names and values are case sensitive.

        It doesn't really clear up my confusion, but so generally I make sure to send it with a capital B.