Query type in GraphQL with Spring Boot

In the previous tutorial, I introduced you to GraphQL, the problems that GraphQL solved for the limitations of RESTful Web Service. I also gave you a brief guide on how to implement GraphQL’s Query type with Spring Boot. In this tutorial, we will learn in more detail how to implement this Query type using Spring Boot.

First, I will create a Spring Boot project with Web and GraphQL Starter as an example:

Result:

As I said in the previous post, to work with GraphQL, we need to define schema .graphqls files. By default, Spring Boot will scan all directories in the project’s classpath src/main/resources to read these schema files.

I will create a folder called graphql in the src/main/resources folder and put the GraphQL schema files in this folder.

As an example, I created a new schema.graphqls file with the following simple initial content:

This query will return the text “Hello World” when we query!

To handle the above Query, we will create a new controller and define a method with the same name as the field name of this Query type, as follows:

As you can see, the hello() method has been annotated with the @QueryMapping annotation so that Spring can scan and map this method name with the field of type Query. Very simple, right?

Behind the sense, the @QueryMapping annotation is implemented using a generic annotation @SchemaMapping:

This @SchemaMapping annotation defines a property typeName which allows us to define the type of GraphQL. Here, our type is Query!

Another property of the @SchemaMapping annotation is the field, which allows Spring to map the field of GraphQL with the name of the method that will handle the request:

By default, if we do not declare a value for this field attribute, its value will be the method name!

If we don’t use the @QueryMapping annotation, we can rewrite the code above using the @SchemaMapping annotation as follows:

For testing convenience, we will add the spring.graphql.graphiql.enabled=true property to enable the use of the GraphiQL tool, in the application.properties file:

Now, if you run this application and query using the hello field above, you will see the following results:

To pass parameters to a Query, we will define an example like this:

In the controller, we will use the @Argument annotation to bind the parameter defined in the Query field with the parameter in the request handle method:

The name attribute of this @Argument annotation allows us to specify which parameters in the method are bound to which parameters in the Query.

Result when we query:

as follows:

Add Comment