How to use GraphQL in Spring: An easy step-by-step tutorial

In this guide, we shall go through steps of getting started with GraphQL in Spring. We will briefly discuss some of the reasons why one may prefer and how to quickly get a prototype up and running in order to know and show you its values on your particular applications.

Why GraphQL?

Since there are standards such as SOAP and REST for exposing APIs, you might be asking yourself why there is a need for GraphQL.

So, let’s consider REST for a while to discuss this. REST is a technique to describe resources on top of HTTP: it resounds that each request is on one specific resource, on the entire resource at that, and none of this has a schema or type system. 

Even though REST architecture is relatively simple and very popular, there are some architectural assumptions or anti-patterns that produce extremely ‘chatty’ APIs that require the client side to hold type interpretation capabilities. Discussing one resource at a time can also lead to things such as, domain-driven design appearing less suitable for REST when in fact they are not.

It is equally relevant here to state that assessing one resource at a time can also make phenomena like domain-driven design less native for the rest.

GraphQL views the problem of fetching data differently; It is a query language like SQL, that enables clients to fetch data however they want it to be returned. 

At its core, there is a query engine that calls the correct data retrievers given the analysis of the query type.

Where REST is a set of principles discussing how a server can present data to a client, GraphQL, on the other hand, is a client-side query language the client uses to tell the server what data it requires. 

This means that a client can more easily ask to join the resources and get only the data it requires on the fly (as in the SQL table join and select where statements) without the server pre-estimating what precise query is about to be issued.

With that in mind, let’s create a model example of an API to operate trains and their routes.

Using SpringInitializr

When you are building a Spring application, https://begin is an effective abbreviation used to express the beginning of a particular event, topic, or program on the computer. Spring.io is a good starting point—a place from which you can reach out to more people easily and want more buttons. 

If you are following along, pick the latest Spring Boot and Java versions, and then select the Spring Web and Spring for GraphQL modules like in this screenshot: If you are following along, pick the latest Spring Boot and Java versions, and then select the Spring Web and Spring for GraphQL modules like in this screenshot:

Then, download the artifact and import it into your favorite IDE; it will contain the answer to the question. Aside from building a skeleton application, it added the following two dependencies: which will fetch us the required Spring GraphQL starting artifacts for creating a Spring-GraphQL enhanced service.

Modeling Resources

Let’s introduce two simple Java records, one called Train and the other called Route: 

But while we are here, one must notice that the two domain objects here are referring to each other simply through a reference, if there was one, and this may not be what many are used to. This is possible because we are going to let the GraphQL engine do that work of joining tables for us.

Declaring the Schema

Recall that one of the benefits is type safety (though, ahem, that’s right, this is also true of SQL). To achieve that, we need to declare a schema / a fundamental structure.

In Spring Boot, you would declare this in a file known as schema. Insert the graphqls in the src/main/resources/graphql directory. It should look something like this: It should look something like this:

The first is generic to all GraphQL schemas and contains some inherent properties of any schema. It is a listing of the query operations of the application. The last two of those send the description of custom data types defined for our GraphQL to the GraphQL. I would like to highlight that `Query` and `Route` are built out of GraphQL types and implemented types and my types.

Declaring Data Fetchers

Since there are two schemas with a direct data relationship in our configuration, which are the query and the Route to Train mapping, it is time to develop two data fetchers using Spring GraphQL.

But in WordPress GraphQL you similarly define data fetchers as you define controllers. Instead of @GetMapping like in the case of a @RestController which maps one GET query to a Java method we use @QueryMapping to map the routeById query. Next, we need to map the ‘route-to-train’ relationship to a Java method using @SchemaMapping.

To add some data to return, let’s create a couple of maps like this: A better way to explore this message now is to continuously keep in mind GraphQL fundamentals before introducing a regular concept like a database.

Now let me provide the current implementation details of each method that we are going to apply, for better understanding. The query method will need to fetch a route by its id, which we can do by querying the routes map like this: 

Running a Few Queries

Great! The server is on standby and has just received a few requests. But how do we send them or rather, how do they come about? Often, cURL, HTTPie, and other tools can be used to send various HTTP-based queries. We need someone who knows how to make a program with the ability to send some GraphQL queries.

Luckily, Spring Boot has one that you can use out of the box and make active by using the property below in the application.properties:

Now it is time to define the interface between Spring Boot and GraphQL, utilizing the query engine.

Start the server by running the main method in TrainsQlApplication, and then navigate to http://$GraphQLEndpointURL/ whilst, For visualization and exploration of GraphQL operations, use $GraphQLEndpointURL/graphiql.

You should see a GraphQL client like this one: In the query section, paste the following query: In the query section, paste the following query:

This query states that you need to know the departing and destination cities for the 4S route by what time the train is leaving, and the number of seats available in the train.

Run the query and you can see a result like this: 

Testing GraphQL Fetchers

Allow me to finalize by performing a test to see if our fetcher is still functional.

Create a new test file in src/test/java named RouteControllerTests and place the following inside:

Oh yes, that’s another document that’s referred to as route details- and it has to be created as well. 

In the graphql-test file which is located at /src/test/resources/createOrders.graphql, make a new file called route details.graphql and place the following: graphql and place the following:

You will recognize this as a query we composed during the demo. Execute it and ensure that it passes.

Conclusion

Here in this article, you have read some of the reasons for the development of GraphQL and how it is not a replacement or competitor to REST but is working on a different set of problems. The next thing you saw was how to go about creating the structure of a simple GraphQL server application. We forward the necessary domain objects and the controller that can accept a query. We also included testing so that it will still work in the future tests were included in the update.

Leave a Reply

Your email address will not be published. Required fields are marked *