Spring RestTemplate vs GraphQL Client

This tutorial is mainly meant for REST API developers, who want to learn how to develop a GraphQL client. It is a comparison of a RestTemplate and GraphQL client.

Ivan Polovyi
Javarevisited
3 min readMay 15, 2022

--

Let's consider a use case where we have an application we call “producer”, which manages information about a customer. This application exposes REST API and GraphQL. The REST API has GET, POST, PUT, PATCH, and DELETE methods which return, create, update, partially update, and delete the customer accordingly. This application has GraphQL as well with a Query and Mutation API which replicates the functionality of a REST API.

If you are interested in REST API vs GraphQL you can check the following materials:

Another application we will call “client” consumes the REST API and GraphQL API of a “producer”.

The complete source code of both applications can be found on a GitHub repository:

To consume a REST API the RestTemplateis used, check the complete code of a class below:

And to consume GraphQL the GraphQLWebClient is used. It is very straightforward. When using the GraphQL client we have to create a query string or a mutation string, if it has variables we have to create a map with variables' names and values, and then use the string to create a request. Then pass a request to the post method of the client. We can save query or mutation string inside the resource directory and then pass their path instead of a query string. Check the client method to update a customer.

The Spring project has a GraphQL Spring Boot starter. It is much easier to use because it is based on annotations. This is a Milestone release at the time of writing, so it is not recommended yet to use it in production. As a bonus for this tutorial, I’ve created one more project that uses Spring boot for GraphQL. The complete code can be found below:

In this case, to consume GraphQL the HttpGraphQlClientis used. Basically, the code is very similar to the previous one and there is not much to explain. Just check it bellow:

To test it the “client” app has a REST API to call the REST client and a separate REST API to call a GraphQL client. The Postman collection is located in the root directory of a project. The short demo video below shows how the “producer” — “client” communication works.

Conclusion

This tutorial was made to show how to implement the GraphQL client. To better understand the examples shown alongside the REST API client, which is an actual standard for API nowadays. Thank you for reading! If you have any questions or suggestions, please feel free to write me on my LinkedIn account.

--

--

Ivan Polovyi
Javarevisited

I am a Java Developer | OCA Java EE 8 | Spring Professional | AWS CDA | CKA | DCA | Oracle DB CA. I started programming at age 34 and still learning.