如何在python中使用github api标记进行请求

时间:2013-07-12 19:15:58

标签: api python-2.7 oauth-2.0 python-requests github-api

我可以使用用户名和密码在python中获取Github api令牌,但是我无法使用该API令牌来请求任何POST / DELETE / PATCH。

我们如何使用Github API-Tokens提出任何请求。 例如,我有API-Token可以说'hbnajkjanjknjknh23b2jk2kj2jnkl2 ...'

现在请求

#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)

但我总是通过401 error消息获取Bad Crediantials

在不输入密码的情况下使用API​​令牌的正确方法是什么

4 个答案:

答案 0 :(得分:17)

首先,我建议使用API​​的包装器。你在这里问了很多问题,可以通过找到你喜欢的API的包装器来简化。有一个用Python here编写的包装器列表。

至于您实际回答的问题,GitHub文档非常明确,您需要发送Authorization header。你的电话实际上是这样的:

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

既然您似乎在使用请求和课程,我可能会大胆地提出建议吗?假设您正在为API创建客户端。你可能有这样一个类:

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)

Session对象将为您处理身份验证(通过令牌或用户名和密码组合)。

另外,如果你最终决定使用github3.py来满足你的API包装需求,那么这里就有一个标签。

答案 1 :(得分:6)

以下是一些可能对您有帮助的代码。

示例:

示例1(auth):

username = 'user'
token = 'token'

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

示例2(标题):

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

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

示例3(删除回购):

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

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

login = requests.delete('https://api.github.com/' + 'repos/' + user + '/' + repo, headers=headers)

示例4(创建回购):

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))

您可能需要查看以下文档:

Requests Docs

Github API docs

我希望这会有所帮助。

答案 2 :(得分:2)

我遵循了API文档,并尝试在对int[] values = new int[] { 5, 5, 5}; int[] weights = new int[] { 9, 9, 9}; 的调用中设置Authorization头。但是,这总是返回401错误。因此,我检查了requests.get()对象的Response属性的标头,发现请求中的request标头已被重写。深入研究源代码后,我发现当请求调用HTTP Basic Auth时,Authorization标头被重写(请参见here)。

因此,解决方案是在调用Authorization时在auth元组中传递令牌。例如:

requests.get()

不幸的是,this answer(目前投票最高的投票器)不起作用,因为该答案中的方法正是我在尝试上述解决方案之前所使用的方法。

答案 3 :(得分:2)

使用requests python 库,您需要将请求Headers 通知Github account API Token

示例:

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

然后你可以调用你想要的资源,例如:

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

您可以在 Github API official documentation

上找到更多详细信息