I wrote a small new Web Panel, which includes GitHub and npm based statistics. Now it is really easy to get GitHub working, because the documentation is really rich and easy to understand. But how is it possible to get some neat stats from npm? The official documentation conceals this, but NOT good enough! Here is the breadcrumb to find the official documentation, before we start using it!

HowTo find the official Documentation

  1. Search for “api.npmjs.com site:docs.npmjs.com” in Google or DuckDuckGo
  2. Go to the entry Registry – NPM Docs (Google) or npm-registry (DuckDuckGo)
  3. Found the Link “https://github.com/npm/npm-registry-couchapp” in the fifth paragraph
  4. Notice the Deprecation Notice
  5. Visit the hidden Link in the “better documenting the existing API” text
  6. Click on the blue “npm/registry repo” link.
  7. Open the folder docs
  8. Finally, touch soft the download-counts.md file with your cursor

 

So it is really easy, and to visualize this process, I also made a small GIF for you:

 

 

HowTo use the official npm API

Now it gets interested, because we going to use this API to get some neat download statistics for our packages. In our example, we’re using PHP and the cURL extension, which should be available on each paid hoster (Free Webhoster may disallow the use of cURL). But before we can start writing our script, we need to understand how the API works and which data the API wants to see and return.

This is the easy part of this article, because npm’s API just allows two (2) _GET methods at all. Both are called in the same way and return either the total download counter, or the downloads made per day. As you can imagine it doesn’t makes a difference, if you want to receive the counter for just a single day (except that the returning format is different). Let us start with the URL, which we need to pass:

https://api.npmjs.org/downloads/$method/$range/$package/

As described above the method variable changes the “counter statistic”, use either point to get a total of all counts or range to get the daily counts. The range can be a keyword (last-day, last-week or last-month), a specific date (“2018-06-17”) or a range (“2018-03-17:2018-06-17”). And the last parameter, package can be a single npm package (such as “tail.select”) or multiple comma-separated ones (like “tail.select,tail.datetime”).

Examples

You can click on the respective examples below to view the returning JSON document. Please Note: You should ALWAYS use the SSL connection (via https:), otherwise erroneous queries can be returned!

Get the total download count of tail.select for the last day:
https://api.npmjs.org/downloads/point/last-day/tail.select
Get the daily download counts of all tail projects for the last week:
https://api.npmjs.org/downloads/range/last-day/tail.select,tail.datetime,tail.writer,tail.bbsolid

Real World Function

You may think, Just show me some code, and yeah it’s time to reveal the secret code. Don’t expect any class construct or the use of a fat library, because it isn’t necessary at all. I mean, we just want to get some neat download statistics from npm, so a small handy solution should handle this already:

<?php 

    function get_npm_count($method, $range, $package){
        if(is_array($package)){
            $package = implode(",", $package);
        }
        $url = "https://api.npmjs.org/downloads/{$method}/{$range}/{$package}";

        // cURL
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);              // Pass the URL
        curl_setopt($curl, CURLOPT_HEADER, false);          // Exclude HTTP Header
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);            // Abort after 30 seconds
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);   // Don't Print, Return
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);   // Follow Redirects
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
           "Accept: application/json"                       // "Expect" a JSON response
        ));
        $content = curl_exec($curl);
        $response = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        // Response
        if($response != 200){
           return false;
        }
        return json_decode($content, true);
    }

The function above is really simply knitted, it just allows the parameters which we need for our API call and build the respective URL. This URL gets passed on the cURL method (setted with the CURLOPT_URL constant), together with some other settings which are described next to it. To summarize it: We don’t want the page header, just the content (expected as JSON response) and follow several redirects to get it, but don’t wait more then 30 seconds.

Last but not least: We check if the returning data is just Okay (which returns as HTTP Status Code 200), decode the JSON response and return it. It isn’t the safest function and maybe you can improve it with some cool tricks, but it already does what it should: Call the npm Web API and return some data.