GraphQL with Java

Mary Reni
Javarevisited
Published in
3 min readApr 19, 2021

Why and when do we need it?

Let us start with an example before going into the specifics.

Consider that we are building an OTT platform. Each user will have an account where he can save his favorite programs. He should be able to access his account from different platforms like Mobile App or browsers.

Each of the platforms will have its own web interfaces, some lean and some extensive.

For learning’s sake, let us assume that the user model is only going to have the below details:

ProgramInfo is going to have the below details:

Now, when we are using Rest API, if we only need the name and country of the account, below are our options:

  • We will need to have a minimal model and a separate API to get the required details
  • Get the entire user details (assume that the user has saved a lot of programs as favourites), making the communication message heavy

As you can see here, the client has no control over what it wants to have, only tje server decides on what the client needs to query on the server.

But if we use GraphQL in the server, the client can request the information it needs to access. I am using Graphql playground tool for communicating with the graphql application I have created.

Below is how the query and the result for the above mentioned scenario looks like.

Or, if the client wants the programIds of the favorite programs of the user, below is how it is going to be.

Interesting, isn’t it?

Let us now implement the code to accomplish this. The first step is to have a graphql schema. Below is the schema that I have defined for our use case. This needs to go in the resources folder as per my implementation.

I have declared two custom models, User and ProgramInfo. ProgramInfo is part of User model.

Next, there is a query declared, the query(userById) would be on the id. In order to receive the user model, the client needs to provide an userId for identifying the requested resource. He can optionally provide the values in the User model that he would like to receive.

Now, we will implement the schema, I am using graphql-java library. I am going to use spring-boot application with maven build. Below dependencies needs to be added in our pom.xml. I am using guava library for parsing the schema file.

With the schema defined above, we need to create wirings for serving the client's request. Below are the essential implementations needed to create a GraphQL instance.

  1. Read the schema defined
  2. Parse the schema and create the wirings
  3. Create a GraphQL instance from the parsed schema

Now we have a GraphQL instance initiated for our defined schema. Start the application and hit the url below with a request body with the required information through graphql playground tool.

References:

GraphQL website: https://graphql.org/learn/

Author’s github repository: https://github.com/mrajaian/graphqlExample

--

--