how to use github api token in python for requesting

softvar picture softvar · Jul 12, 2013 · Viewed 25.4k times · Source

I'm able to obtain Github api token in python using username and password but i'm not able to use that API-Token for requesting any POST/DELETE/PATCH.

How do we use Github API-Tokens for making any request. For eg, i have API-Token lets say 'hbnajkjanjknjknh23b2jk2kj2jnkl2...'

now for requesting

#i'm providing username and API-Token in headers like    
self.header = {'X-Github-Username': self.username,
               'X-Github-API-Token': self.api_token                  
              }
#then requesting(post) to create a gist
r = requests.post(url, headers=headers)

But i'm always getting 401 error with Bad Crediantials message.

What's the proper way to use API-Tokens without inputting the password

Answer

Ian Stapleton Cordasco picture Ian Stapleton Cordasco · Jul 13, 2013

For one, I would recommend using a wrapper for the API. You're asking a lot of questions on here that could be simplified by finding a wrapper whose API you appreciate. There's a list of wrappers written in Python here.

As for your actually answering your question, the GitHub documentation is fairly clear that you need to send the Authorization header. Your call would actually look like this:

self.headers = {'Authorization': 'token %s' % self.api_token}
r = requests.post(url, headers=self.headers)

Since it seems like you're using requests and a class, might I be so bold as to make a recommendation? Let's say you're doing something like making a client for the API. You might have a class like so:

class GitHub(object):
    def __init__(self, **config_options):
        self.__dict__.update(**config_options)
        self.session = requests.Session()
        if hasattr(self, 'api_token'):
           self.session.headers['Authorization'] = 'token %s' % self.api_token
        elif hasattr(self, 'username') and hasattr(self, 'password'):
           self.session.auth = (self.username, self.password)

    def call_to_the_api(self, *args):
        # do stuff with args
        return self.session.post(url)

The Session object will take care of the authentication for you (either by the tokens or username and password combination).

Also, if you end up deciding to use github3.py for your API wrapper needs, there's a tag on here for it.