I'm attempting to read some data out of GitHub with their v4 (GraphQL) API. I've written a Java client that is working fine up until I start replacing some of the query with GraphQL fragments.
I was using GraphiQL to initially test my queries, and adding fragments was pretty simple in there. However, when translating to JSON, I haven't figured out the correct format. I've tried:
{ "query": "{ ... body_of_query ... } fragment fragname on Blob { byteSize text }" }
{ "query": "{ ... body_of_query ... }, fragment fragname on Blob { byteSize text }" }
{ "query": "{ ... body_of_query ... }", "fragment": "{fragname on Blob { byteSize text } }" }
EDIT: Adding for @Scriptonomy:
{
query {
search(first:3, type: REPOSITORY, query: \"language:HCL\") {
edges {
node {
... on Repository {
name
descriptionHTML
object(expression: \"master:\") {
... on Tree {
...recurseTree
}
}
}
}
cursor
}
pageInfo {
endCursor
hasNextPage
}
}
}
fragment recurseTree on Tree {
entries {
name
type
}
}
I'm sure it would be fun and all to keep throwing random variations on this, and my morning has been huge fun searching various GraphQL docs and blogs on fragments, and I may have even actually guessed the correct answer but had mismatched parens (I'm just using hardcoded JSON until I know the format -- perhaps not the wisest choice looking back on it).
I'm hoping that someone may know the correct format and set me on the correct course before I keel over from GraphQL-doc over-exposure.
There is no need to translate GraphQL Query to JSON. This would be your query:
For future users, and people like me who stumbled upon this hurdle.
Query needs to be sent in the given order;
Hope this will help others.
Fragments are sent in the same property of the JSON body as the query itself. You can see an example for using fragments here.
A valid GraphQL request is usually either a GET request that encodes the query as URL query parameter, or a POST request with a JSON body. The JSON body has one required key,
query
and one optional field,variables
. In your case, the JSON needs to look like this:That is the
JSON.stringify
version of the verbatim query string in your question.I recommend you to run queries from a GraphiQL instance connected to your GitHub GraphQL API and look into the network request. You can copy the GraphQL request as cuRL to see how the JSON body needs to look like.
If you still obtain a 400, please share some code, because that means your request was malformed, so it probably never hit the GraphQL parser in the first place.