6

Here is an example of a cURL query to the GitHub api v4 that keeps returning an error:

curl -H "Authorization: bearer token" -X POST -d " \
 { \
   \"query\": \"query { repositoryOwner(login: \"brianzelip\") { id } }\" \
 } \
" https:\/\/api.github.com\/graphql

The error that is returned:

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

Why do I keep getting this error?


According to the GH api v4 docs about forming query calls, the above cURL command is valid. Here's what the docs say that backs up my claim that the above cURL command is valid:

curl -H "Authorization: bearer token" -X POST -d " \
 { \
   \"query\": \"query { viewer { login }}\" \
 } \
" https://api.github.com/graphql

Note: The string value of "query" must escape newline characters or the schema will not parse it correctly. For the POST body, use outer double quotes and escaped inner double quotes.

When I enter the above query into the GitHub GraphQL API Explorer, I get the expected result. The format of the above cURL command looks like this for the GH GraphQL Explorer:

{
  repositoryOwner(login: "brianzelip") {
    id
  }
}
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
Brian Zelip
  • 2,909
  • 4
  • 33
  • 45
  • Isn't it awesome how GraphQL Explore parses the JSON correctly, but when using the API using the exact same query it's problematic. – bart Jan 15 '18 at 10:01

1 Answers1

6

You have to escape nested double quotes in query JSON field, your actual body would be :

{
 "query": "query { repositoryOwner(login: \"brianzelip\") { id } }"
}

So replace \"brianzelip\" with \\\"brianzelip\\\" :

curl -H "Authorization: bearer token" -d " \
 { \
   \"query\": \"query { repositoryOwner(login: \\\"brianzelip\\\") { id } }\" \
 } \
" https://api.github.com/graphql

You can also use single quotes instead of double quotes to wrap the body :

curl -H "Authorization: bearer token" -d '
 {
   "query": "query { repositoryOwner(login: \"brianzelip\") { id } }"
 }
' https://api.github.com/graphql

You could also use heredoc :

curl -H "Authorization: bearer token" -d @- https://api.github.com/graphql <<EOF
{
    "query": "query { repositoryOwner(login: \"brianzelip\") { id } }"
}
EOF
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
  • How to support multiple Query schema ?. My query schema as { viewer { login } codesOfConduct { body id key name resourcePath url } – BASS KARAN Jul 01 '20 at 14:35