how to use github api token in python for requesting

how to use github api token in python for requesting

For one, I would recommend using a wrapper for the API. Youre asking a lot of questions on here that could be simplified by finding a wrapper whose API you appreciate. Theres 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 =, headers=self.headers)

Since it seems like youre using requests and a class, might I be so bold as to make a recommendation? Lets say youre 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.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

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 for your API wrapper needs, theres a tag on here for it.

Heres some code that might help you out.


Example 1 (auth):

username = user
token = token

login = requests.get(, auth=(username,token))

Example 2 (headers):

headers = {Authorization: token  + token}

login = requests.get(, headers=headers)

Example 3 (delete repo):

user = username
repo = some_repo # Delete this repo

headers = {Authorization: token  + token}

login = requests.delete( + repos/ + user + / + repo, headers=headers)

Example 4 (create repo):

repo = some_repo
description = Created with api

payload = {name: repo, description: description, auto_init: true}

login = + user/repos, auth=(user,token), data=json.dumps(payload))

You might want to take a look at the following docs:

Requests Docs

Github API docs

I hope this helps.

how to use github api token in python for requesting

Using the requests python library, you need to inform the Github account API Token on the request Headers.


authorization = ftoken {token}
headers = {
    Accept: application/vnd.github.v3+json,
    Authorization : authorization,

Then you can call the resource you wish, example:

r =

You can find more details on the Github API official documentation

Leave a Reply

Your email address will not be published. Required fields are marked *