如何使用Python使用Github GraphQL API?

问题描述:

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

我已经使用Github上GraphQl探险通过这段代码找到仓库的名单:

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

石墨烯是一种用于构建GraphQL的API不消耗他们。您是否看到:https://github.com/graphql-python/gql

这是一个Python的GraphQL客户端。

希望有帮助。

+0

感谢您的回答。我研究了'gql',但是如何使用Github进行身份验证。现在,我想通过编写我自己的库 –

+1

@VaibhavSingh来解决这个问题,遵循GitHub文档(https://developer.github.com/v4/guides/forming-calls/#authenticating-with-graphql),您需要生成一个像https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/的访问令牌。 然后,您必须将您的令牌传递到'Authorization'头部,就像https://developer.github.com/v4/guides/forming-calls/#communicating-with-graphql。 Cheers, – Yasss

+2

@VaibhavSingh您还可以使用图形客户端GraphiQL https://github.com/graphql/graphiql来探索GraphQL API并在将它们写入python之前尝试查询。祝你好运 ! – achedeuzot

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

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

感谢您的回答!所以,如果我想通过添加一些带默认参数的函数来定制我的json,那么这个疑问就很小。所以我会在默认参数中添加'first:10',如果我想编辑,我可以通过传递'first:30'来覆盖。我知道这是一个愚蠢的问题,但你能帮我吗 –

+0

@VaibhavSingh我不确定你的措辞是否正确。再次解释它。 – sreenivas

+0

现在json被我们修改了,我们会从GraphQL中得到预期的结果,但是如果我想要的话,我可以自定义json buy传递函数中的函数,并且可以根据用户更改查询。现在它在程序中被硬编码 –