43

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

1
  • can't we use something like requests.post(....,auth=api_token) instead of auth=(username,password) Commented Jul 12, 2013 at 19:21

5 Answers 5

51

Here's some code that might help you out.

Examples:

Example 1 (auth):

username = 'user'
token = 'token'

login = requests.get('https://api.github.com/search/repositories?q=github+api', auth=(username,token))

Example 2 (headers):

headers = {'Authorization': 'token ' + token}

login = requests.get('https://api.github.com/user', headers=headers)
print(login.json())

Example 3 (delete repo):

user = 'username'
repo = 'some_repo' # Delete this repo

headers = {'Authorization': 'token ' + token}

login = requests.delete('https://api.github.com/' + '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 = requests.post('https://api.github.com/' + '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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! This explanation really helped!
requests will possibly complain: ssl error, as use https (tls/ssl) without certificate.
@NikolaiEhrhardt If you get SSL error's on requests, try this: CERT_PATH=$(python3 -m certifi) export SSL_CERT_FILE=${CERT_PATH} export REQUESTS_CA_BUNDLE=${CERT_PATH}
Its just a hint. Or an insuffiency of your answer, to be a little annoying ;)
39

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.

3 Comments

using self.session.headers['Authorization'] = 'token %s' % self.api_token and not using auth=(username,password) inside requests.post() is responding back with {u'message': u'Not Found'}
You don't use requests.post with this, you use self.session.post.
It's supposed to be session.get (not post) because the latter responds back with 404
5

I followed the API documentation and tried to set the Authorization header in my call to requests.get(). However, this always returned a 401 error. So I checked the headers from Response object's request attribute and found that the Authorization header from my request had been rewritten. After a little digging in the source code, I found that when the request calls for HTTP Basic Auth, the Authorization header gets rewritten (see here).

So, the solution was to pass the token in an auth tuple when calling requests.get(). For example:

requests.get('https://api.github.com/notifications', auth=(my_username, my_token))

Unfortunately, this answer (currently the highest-voted one) won't work, as the method from that answer is precisely what I was using before trying the solution above.

Comments

4

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

Example:

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

Then you can call the resource you wish, example:

r = requests.post(
    url=url,
    data=json_data,
    headers=headers
    )

You can find more details on the Github API official documentation

1 Comment

This does not work. Getting 403 complaining about need to authorize token for the org (while the same token works in command line in Curl and it works with auth= as suggested in other answer).
0
from github import Github
import requests
import pandas as pd
import datetime
token='.....................'
g=Github(token,per_page=10000)
repos=g.search_repositories(query="q:rgpd")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.