Alex Alex - 1 year ago 329
Python Question

GitHub GraphQL API Problems parsing JSON

What is wrong here?

query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'

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

r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query+'\"}',headers=headers)

print (r2.json())


i got

{'message': 'Problems parsing JSON', 'documentation_url': 'https://developer.github.com/v3'}


but this snippet of code below works correctly

query1= '''{ viewer { login name } }'''

headers = {'Authorization': 'token xxx}

r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query1+'\"}',headers=headers)

print (r2.json())


i tried out to change strings (" on ' or with \" and so on) but it doesn't work.

Answer Source

The problem is related with the double quotes ("). On the first snippet, when you join the '{"query": \"'+query+'\"}' with the query variable, you get the following result:

{"query": "{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }"}

Notice how the double quote from "ALEXSSS" are not escaped, therefore the resultant string is not a json valid format.

When you run the second snippet, the resultant string is:

{"query": "{ viewer { login name } }"}

which is a valid json string.

The easiest and best solution is simply use the JSON library instead of trying to do it manually, so you won't need to worry about escaping characters.

import json

query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}

r2=requests.post('https://api.github.com/graphql', json.dumps({"query": query}), headers=headers)

print (r2.json())

But remember that you could also just escape the characters on the query manually:

query='{ repositoryOwner(login : \"ALEXSSS\") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}

r2=requests.post('https://api.github.com/graphql', '{"query": "'+query1+'"}', headers=headers)

print (r2.json())

it works as expected :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download