Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 421
Holy Mackerel Avatar asked May 14 '14 16:05

Holy Mackerel


People also ask

How do I get an API token in Python?

Obtain Access Token Use your client ID and client secret to obtain an auth token. You will add the auth token to the header of each API request. The following Python example shows how to obtain an auth token and create the Authorization header using the token.

How do you pass a bearer token in Python?

To send a GET request with a Bearer Token authorization header using Python, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.


2 Answers

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())
like image 88
Holy Mackerel Avatar answered Oct 11 '22 04:10

Holy Mackerel


I realize this question is a few years old, but if anyone wants to auth with a personal access token while also using the requests.get and requests.post methods you also have the option of using the method below:

request.get(url, data=data, auth=('user','{personal access token}')) 

This is just basic authentication as documented in the requests library, which apparently you can pass personal access tokens to according to the github api docs.

From the docs:

Via OAuth Tokens Alternatively, you can use personal access tokens or OAuth tokens instead of your password.

curl -u username:token https://api.github.com/user

This approach is useful if your tools only support Basic Authentication but you want to take advantage of OAuth access token security features.

like image 40
Abe Miessler Avatar answered Oct 11 '22 03:10

Abe Miessler