Search code examples
pythongithubgithub-api

Unable to use Github API with authentication tuple


query = "https://api.github.com/repos/rhinstaller/anaconda/tags" 

response = requests.get(query,auth=(self.username,self.token))
response.raise_for_status()  # raises exception when not a 2xx 
    if response.status_code != 204:
        try:
            data = response.json()
            print("data = ",data)
        except:
            print("0")

The above code always returns data as empty whereas response = requests.get(query) will still work until the rate is exceeded.

What could be the reason behind this? Previously, github APIs used to work fine with this kind of tuple based authentication in Python.

Edit: print(response.__dict__) yields :

{'_content': b'{"message":"Bad credentials","documentation_url":"https://docs.github.com/rest"}', '_content_consumed': True, '_next': None, 'status_code': 401, 'headers': {'Server': 'GitHub.com', 'Date': 'Sat, 22 Oct 2022 14:01:13 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '80', 'X-GitHub-Media-Type': 'github.v3; format=json', 'X-RateLimit-Limit': '60', 'X-RateLimit-Remaining': '56', 'X-RateLimit-Reset': '1666449620', 'X-RateLimit-Used': '4', 'X-RateLimit-Resource': 'core', 'Access-Control-Expose-Headers': 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'X-Frame-Options': 'deny', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '0', 'Referrer-Policy': 'origin-when-cross-origin, strict-origin-when-cross-origin', 'Content-Security-Policy': "default-src 'none'", 'Vary': 'Accept-Encoding, Accept, X-Requested-With', 'X-GitHub-Request-Id': 'D2F0:13300:1D277E2:1D98791:6353F7A9'}, 'raw': <urllib3.response.HTTPResponse object at 0x7f596e77da90>, 'url': 'https://api.github.com/repos/rhinstaller/anaconda/tags', 'encoding': 'utf-8', 'history': [], 'reason': 'Unauthorized', 'cookies': <RequestsCookieJar[]>, 'elapsed': datetime.timedelta(microseconds=176914), 'request': <PreparedRequest [GET]>, 'connection': <requests.adapters.HTTPAdapter object at 0x7f596e76cbd0>}

Solution

  • The error says you have incorrect credentials

    import requests
    from requests.auth import HTTPBasicAuth
      
    # Making a get request
    response = requests.get('https://api.github.com/user, ',
                auth = HTTPBasicAuth('user', 'token'))
      
    # print request object
    print(response)
    

    Ref: https://www.geeksforgeeks.org/authentication-using-python-requests/