21

我想使用 Github GraphQl v4 API 从 Github 访问详细信息。我找到了Graphene库,但我不确定如何在 Python 中使用个人访问令牌进行身份验证。
我尝试在 Google 上搜索,但找不到任何示例。它是一个 Python 库,可以创建图形模式而不是使用它们,我尝试使用“请求”但失败了。我如何进行身份验证并找到存储库列表?

我使用 Github GraphQl explorer 通过以下代码查找存储库列表:

viewer {
repositories(first: 30) {
  totalCount
  pageInfo {
    hasNextPage
    endCursor
  }
  edges {
    node {
      name
    }
  }
}
4

4 回答 4

34

与 rest 不同,graphql 只有一个端点。您只需POST要将查询作为 json 对象执行。您应该提供您api_tokengithub获得的信息作为标题的一部分。

import requests

url = 'https://api.github.com/graphql'
json = { 'query' : '{ viewer { repositories(first: 30) { totalCount pageInfo { hasNextPage endCursor } edges { node { name } } } } }' }
api_token = "your api token here..."
headers = {'Authorization': 'token %s' % api_token}

r = requests.post(url=url, json=json, headers=headers)
print (r.text)
于 2017-09-18T04:10:31.380 回答
9

Graphene 用于构建 GraphQL API,而不是用于使用它们。

你看到了吗:https ://github.com/graphql-python/gql ?

它是 Python 的 GraphQL 客户端。

希望这会有所帮助。

于 2017-08-31T11:41:10.663 回答
3

As previous answers mentioned, calling GraphQL is as simple has making a POST request with the query string. However, if you're on Python3 want something more advanced that'll also verify your queries during build and generate typed data-class response classes for you check out the new GQL library: https://github.com/ekampf/gql

于 2018-12-31T05:09:19.617 回答
3

对于 GitHub,有一个使用 Github GraphQL API 和 Python 3 的示例

https://gist.github.com/gbaman/b3137e18c739e0cf98539bf4ec4366ad

(检查链接,因为它有很多评论,包括更好的身份验证代码)

# An example to get the remaining rate limit using the Github GraphQL API.

import requests

headers = {"Authorization": "Bearer YOUR API KEY"}


def run_query(query): # A simple function to use requests.post to make the API call. Note the json= section.
    request = requests.post('https://api.github.com/graphql', json={'query': query}, headers=headers)
    if request.status_code == 200:
        return request.json()
    else:
        raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))

        
# The GraphQL query (with a few aditional bits included) itself defined as a multi-line string.       
query = """
{
  viewer {
    login
  }
  rateLimit {
    limit
    cost
    remaining
    resetAt
  }
}
"""

result = run_query(query) # Execute the query
remaining_rate_limit = result["data"]["rateLimit"]["remaining"] # Drill down the dictionary
print("Remaining rate limit - {}".format(remaining_rate_limit))

并且有很多 Python GraphQL 客户端库:

官方列表在https://graphql.org/code/#python
(向下滚动,客户端库在服务器库之后)

于 2021-05-27T10:17:24.277 回答