Sending GraphQl query in java

HemaSundar picture HemaSundar · Apr 28, 2016 · Viewed 19.9k times · Source

I am new to GraphQL. I know it is very basic question. But tried spending lot of time and i couldn't make it.

My requirement is i need to send GraphQL query by using graphql-java api methods from a java class.

Here is the query:

{
  contentItem(itemId: 74152479) {
    slug
    updatedAt
    contributors {
      id
      isFreeForm
      name
    }
  }
}

Answer

ch33hau picture ch33hau · May 4, 2016

First, you have to illustrate more on your problem, from your sample query I can't actually see which part you are having problem, it could be in argument, nested object, or data fetcher

I'm new to GraphQL(java) as well, instead of sharing the direct answer with you, I intended to show you how I resolve the similar problem.

graphql-java actually did a great job in their test cases. You can refer here: https://github.com/andimarek/graphql-java/tree/master/src/test/groovy/graphql to get some ideas on how to create and query GraphQL schema.

Arguments

I found a similar case like yours in here: https://github.com/andimarek/graphql-java/blob/master/src/test/groovy/graphql/StarWarsSchema.java#L131

newFieldDefinition()
    .name("human")
    .type(humanType)
    .argument(newArgument()
        .name("id")
        .description("id of the human")
        .type(new GraphQLNonNull(GraphQLString))
        .build())
    .dataFetcher(StarWarsData.getHumanDataFetcher())
    .build())

In this case, only one argument is defined, which is id. new GraphQLNonNull(GraphQLString) tells us this is is a mandatory string argument.

Fields

For fields, it is defining in humanType, you can refer to https://github.com/andimarek/graphql-java/blob/master/src/test/groovy/graphql/StarWarsSchema.java#L51. Nested fields is just another type with some fields, eg, .type(nestedHumanType)

Data Fetcher

After all, you might to process the argument id and return some data. You can refer to the example here: https://github.com/andimarek/graphql-java/blob/master/src/test/groovy/graphql/StarWarsData.groovy#L84

To make my code looks cleaner, normally I will create a separate class for DataFetcher, eg:

public class HumanDataFetcher implements DataFetcher {
    @Override
    public Object get(DataFetchingEnvironment environment) {
        String id = (String)environment.get("id");
        // Your code here
    }
}

Hope this helps.