Search code examples
pythonapigithubauthorizationurllib2

Access Github API using Personal Access Token with Python urllib2


I am accessing the Github API v3, it was working fine until I hit the rate limit, so I created a Personal Access Token from the Github settings page. I am trying to use the token with urllib2 and the following code:

from urllib2 import urlopen, Request

url = "https://api.github.com/users/vhf/repos"
token = "my_personal_access_token"
headers = {'Authorization:': 'token %s' % token}
#headers = {}

request = Request(url, headers=headers)
response = urlopen(request)
print(response.read())

This code works ok if I uncomment the commented line (until I hit the rate limit of 60 requests per hour). But when I run the code as is I get urllib2.HTTPError: HTTP Error 401: Unauthorized

What am I doing wrong?


Solution

  • I don't know why this question was marked down. Anyway, I found an answer:

    from urllib2 import urlopen, Request
    url = "https://api.github.com/users/vhf/repos"
    token = "my_personal_access_token"
    
    request = Request(url)
    request.add_header('Authorization', 'token %s' % token)
    response = urlopen(request)
    print(response.read())