Metacpan Download URL

This morning I read that we can now get the download URL for a CPAN module from the Metacpan API! For example, if we visit this URL

$ curl https://api-v1.metacpan.org/download_url/Path::Tiny
{
   "download_url" : "https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/Path-Tiny-0.096.tar.gz",
   "version" : "0.096",
   "status" : "latest",
   "date" : "2016-07-03T01:36:29"
}

we get this blob of JSON. If we just want the URL, we could run it through jq

$ curl -s https://api-v1.metacpan.org/download_url/Path::Tiny | jq .download_url
"https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/Path-Tiny-0.096.tar.gz"

OALDERS does the same thing in Perl, but it uses three different CPAN modules. HTTP::Tiny is in the standard library, right? Oh, but it needs help from IO::Socket::SSL and Net::SSLeay to get an https URL. And we still need something to encode the URI and something to decode the JSON. Here’s my first crack at it.

#!/usr/bin/env perl

use v5.24;
use warnings;
use HTTP::Tiny;
use JSON;
use URI::Encode qw(uri_encode);

my $module = shift // die "Usage: $0 module\n";

my $uri = uri_encode("https://api-v1.metacpan.org/download_url/$module");

my $res = HTTP::Tiny->new->get($uri);
die "Failed!\n" unless $res->{success};

say decode_json($res->{content})->{download_url};

We didn’t need to use LWP, but we still needed help from CPAN. If we can’t do it with the standard library, why not use Mojolicous? This is a web framework, of course, but it includes some excellent client-side tools too. Here is the same thing using the Mojolicious user agent and JSON decoder.

#!/usr/bin/env perl

use v5.24;
use warnings;
use Mojo::UserAgent;

my $module = shift // die "Usage: $0 module\n";

say Mojo::UserAgent->new
    ->get("https://api-v1.metacpan.org/download_url/$module")
    ->res
    ->json
    ->{download_url};

We can even make it a one-liner using the delightful ojo module!

$ perl -Mojo -E 'say g("https://api-v1.metacpan.org/download_url/".shift)->json->{download_url}' Path::Tiny
https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/Path-Tiny-0.096.tar.gz

I’m a little disappointed that it’s not easy to do something as simple as this with just the standard library, but if we use CPAN then we have lots of choices. TMTOWTDI!

Metacpan Download URL