Search code examples
jsonpython-3.xgraphqlpython-3.7

KeyError: 'data' in python3


I am using graphql in order to show the number of pull requests made by a user. The query works fine when I ran it on the graphql explorer by GitHub. However when I run the script, it shows KeyError and that the expected value is string. Even though the username entered is converted to a string.

Here's the code:

accessToken = "###################################"        
headers = {"Authorization": "bearer "+ accessToken }

    def getpullRequests(username):
        topic_query = """
        query {
        repositoryOwner(login:""" + str(username) + """) {
            login 
            ... on User {
            name
            avatarUrl
            pullRequests(last: 100){
                nodes{
                id
                createdAt
                additions
                deletions
                }
            }
            } 
        }
        } 
        """
        request = requests.post('https://api.github.com/graphql', json={'query': topic_query}, headers=headers)
        if request.status_code == 200:
            result = request.json()
            prsdata = {}
            for pr in result['data']['repositoryOwner']['pullRequests']['nodes']:
                prdata = {}
                if re.match(r'^2019-10', pr['createdAt']):
                    prdata['createdAt'] = pr['createdAt']
                    prdata['additions'] = pr['additions']
                    prdata['deletions'] = pr['deletions']
                    prsdata[pr['id']] = prdata
            if prsdata:
                print(prsdata)
            else:
                print("No PRs made in Hacktoberfest")

    if __name__ == "__main__":
        username = input("Enter the GitHub username: ")
        getpullRequests(username)

However on debugging after some tries I found out that the problem is with this line:

for pr in result['data']['repositoryOwner']['pullRequests']['nodes']:

On running the code, the error I face is :

Enter the GitHub username: adiaux
Traceback (most recent call last):
  File "script.py", line 47, in <module>
    getpullRequests(username)
  File "script.py", line 33, in getpullRequests
    for pr in result['data']['repositoryOwner']['pullRequests']['nodes']:
KeyError: 'data'

Someone please help :)


Solution

  • I found a solution. Basically I used the graphQL variables and made the variable into a dict, like this:

     variables=dict({
            "name":str(username)
        })
    

    However accordingly I modified the the query by including:

     query ($name:String!){
        repositoryOwner(login:$name){
            login 
            ... on User {
            name
            avatarUrl
            pullRequests(last: 100){
                nodes{
                id
                createdAt
                additions
                deletions
                }
            }
            } 
        }
        }
    

    Thanks to whoever tried to solve this :)