Queries

Query resolvers

To maintain strong typing and intuitive design, it is common to represent GraphQL types with equivalent Java classes, and fields with methods. graphql-java-tools defines two types of classes: data classes, which model the domain and are usually simple POJOs, and resolvers, that model the queries and mutations and contain the resolver functions. Often, both are needed to model a single GraphQL type.

The schema so far looks like this:

type Link {
  url: String!
  description: String!
}

type Query {
  allLinks: [Link]
}

schema {
  query: Query
}

To model it, two classes are needed: Link and Query.

You should also create a LinkRepository class that will neatly isolate the concern of saving and loading links from the storage. This also makes future extensions and refactoring a lot easier. For now, the links will only be kept in memory.

Returning links

Unlike the Link POJO, Query models behavior, as it contains the resolver for the allLinks query.

Notice how the schema-building logic got extracted into a separate method for easier future additions.

If you now open http://localhost:8080/graphql?query={allLinks{url}} you’ll see your very first GraphQL query executing and giving you the result looking like this:

{
  "data": {
    "allLinks": [
      {
        "url": "http://howtographql.com"
      },
      {
        "url": "http://graphql.org/learn/"
      }
    ]
  }
}

It is now appropriate to feel good about yourself 😎

Testing with GraphiQL

GraphiQL is an in-browser IDE allowing you to explore the schema, fire queries/mutations and see the results.

Arrow to the Docs button in top right corner

If you type the same query from above into the left panel (notice the auto-completion!), you should get the same result but nicely formatted this time. You can also click this link.

Arrow to play button to run

Keep using GraphiQL to test out queries and mutation as you follow the tutorial.

Unlock the next chapter
Is a special client required to query a GraphQL server?
Yes, and there is an implementation in each language
Yes, you need GraphiQL to create and issue queries
No, GraphQL servers are always exposed over HTTP
No, a GraphQL server could be exposed over any transport