28

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?

1
  • Add a user agent header or just use the module(s) on npm for the github API. Commented Oct 7, 2016 at 7:10

6 Answers 6

74

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);
Sign up to request clarification or add additional context in comments.

Comments

7

From C# and using HttpClient you can do this (tested on latest .Net Core 2.1):

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    client.DefaultRequestHeaders.UserAgent.TryParseAdd("request");//Set the User Agent to "request"

    using (HttpResponseMessage response = client.GetAsync(endPoint).Result)
    {
        response.EnsureSuccessStatusCode();
        responseBody = await response.Content.ReadAsByteArrayAsync();
    }
}

Thanks

Comments

0

If Github API is responding with status Code : 403, It simply mean that your API fetching limit has been exceeded please wait for 1 min and again fetch then you will get your data,

Comments

0

ANGULAR

I had the same issue where I got 403 rate limit exceeded. I tried setting up the Authorization header using new HttpHeaders from angular/common but the header still failed. The code that failed is:

getUser(username: string): Observable<any> {
    this.headers.set('Authorization', `token ${this.ACCESS_TOKEN}`);
    const endpoint = `https://api.github.com/users/${username}`;
    return this.http.get(endpoint, {
      headers: this.headers
    }).pipe(response => {
      return response
    });
  }

The code that worked:

getUser(username: string): Observable<any> {
    const endpoint = `https://api.github.com/users/${username}`;
    return this.http.get(endpoint, {
      headers: {
        Authorization: `token ${this.ACCESS_TOKEN}`,
      }
    }).pipe(response => {
      return response
    });
  }

In this case, I directly set the header in the request headers segment.

Comments

0

This answers the question and as a bonus shows you how to check if there is a new release

You need to add a User-agent to the Request

request.UserAgent = "YourRepoName";

    internal class Tag
    {
        [JsonProperty("tag_name")]
        public string TagName { get; set; }
    }

    /// <summary>
    /// Use the Github API to Check for Updates
    /// </summary>
    /// <returns></returns>
    public static Task<string> CheckUpTodate()
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/HypsyNZ/BinanceTrader.NET/releases");
            request.UserAgent = new Random(new Random().Next()).ToString();

            var response = request.GetResponse();
            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string readerOutput = reader.ReadToEnd();

                List<Tag>? deserializedString = JsonConvert.DeserializeObject<List<Tag>>(readerOutput);
                if (deserializedString != null)
                {
                    if (deserializedString.Count > 0)
                    {
                        Tag tagOnFirstRelease = deserializedString.FirstOrDefault();
                        if ("v" + ObservableObject.Version == tagOnFirstRelease.TagName)
                        {
                            return Task.FromResult("Up To Date");
                        }
                        else
                        {
                            return Task.FromResult("Update Available: " + tagOnFirstRelease.TagName);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // Error
        }

        return Task.FromResult("Unknown");
    }

Comments

0

You can fetch the reset time(unix timestamp in seconds) when the rate limit is no more.

curl -L \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer <YOURE BEARER TOKEN>" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/rate_limit | jq .

Here is mine

{
  "rate": {
    "limit": 5000,
    "used": 43,
    "remaining": 4957,
    "reset": 1726650736
  }
}

rate.reset 1726650736 is the time when you're rate limit will be removed, wait until that time.

Put it in https://www.epochconverter.com/

1726650736 corresponds to GMT: Wednesday, September 18, 2024 9:12:16 AM

Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.