node.jsrequestgithub-api

Github API is responding with a 403 when using Request's request function


I am trying to make a request to github's API. Here is my request:

var url = 'https://api.github.com/' + requestUrl + '/' + repo + '/';

request(url, function(err, res, body) {
    if (!err && res.statusCode == 200) {

        var link = "https://github.com/" + repo;
        opener(link);
        process.exit();

    } else {
        console.log(res.body);
        console.log(err);
        console.log('This ' + person + ' does not exist');
        process.exit();
    }

});

This is what I get for my response:

Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes.

I have used the exact same code in the past, and it has worked. No errors are being thrown by request. Now I am confused with why I am getting a 403 (Forbidden)? Any solutions?


Solution

  • As explained in the URL given in the response, requests to GitHub's API now require a User-Agent header:

    All API requests MUST include a valid User-Agent header. Requests with no User-Agent header will be rejected. We request that you use your GitHub username, or the name of your application, for the User-Agent header value. This allows us to contact you if there are problems.

    The request documentation shows specifically how to add a User-Agent header to your request:

    var request = require('request');
    
    var options = {
      url: 'https://api.github.com/repos/request/request',
      headers: {
        'User-Agent': 'request'
      }
    };
    
    function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
        var info = JSON.parse(body);
        console.log(info.stargazers_count + " Stars");
        console.log(info.forks_count + " Forks");
      }
    }
    
    request(options, callback);