Github API is responding with a 403 when using Request's request function
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 noUser-Agent
header will be rejected. We request that you use your GitHub username, or the name of your application, for theUser-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);
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