VOOZH about

URL: https://www.geeksforgeeks.org/advance-java/how-to-integrate-and-call-a-graphql-api-in-a-java-spring-boot-application/

⇱ How to Integrate and Call a GraphQL API in a Java Spring Boot Application? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Integrate and Call a GraphQL API in a Java Spring Boot Application?

Last Updated : 23 Jul, 2025

GraphQL is a more flexible query language and runtime for APIs that lets clients request exactly the data they need by making data fetching more efficient. Compared to REST, GraphQL allows clients to define the exact structure of the response, making data retrieval smoother and more efficient. Integrating GraphQL with Java applications, especially in microservices, can boost data fetching speed and overall performance.

In this article, we will learn how to make a call to a GraphQL service from a Java application using Spring Boot and graphql-java.

Prerequisites:

  • Basic knowledge of Java and Spring Boot.
  • Basic knowledge of the GraphQL.
  • Maven for building dependency management.
  • JDK and IntelliJ IDEA installed in your system.

Calling a GraphQL Service From a Java Application

To call a GraphQL service, it is necessary to understand the following concepts:

  • What is GraphQL?
  • Differences between GraphQL and REST
  • Using WebClient for GraphQL API interaction

GraphQL

GraphQL is an API query language that allows clients to specify exactly which data they need. Compared to REST, it is more efficient, as it supports:

  • Client-Specified Queries: The client defines the response structure, avoiding over-fetching and under-fetching of data.
  • Single Endpoint: Unlike REST, GraphQL uses one endpoint to handle all queries, mutations, and subscriptions.
  • Queries and Mutations:
    • Queries are used for data retrieval (similar to GET requests).
    • Mutations modify server data (similar to POST, PUT, or DELETE requests).
  • GraphQL Schema: Defines the data types and relationships available through the API, serving as a contract between server and client.

Setting Up the Java Application to Call GraphQL

To call a GraphQL service from Java, the main steps are defining the query, sending it to the GraphQL endpoint, and processing the response.

1. Define the GraphQL Query

GraphQL queries are JSON objects with a "query" key. For example:

{
"query": "query { users { id name email } }"
}

In this query, we request each user's id, name, and email.

2. Use WebClient to Send the Query

WebClient is a non-blocking HTTP client from Spring WebFlux. It is an alternative to RestTemplate, providing better performance and flexibility for modern web applications.

Why Use WebClient?

  • Non-blocking: Allows better handling of asynchronous operations.
  • Reactivity: Supports reactive programming, useful for handling data streams.

Constructing the WebClient: Configure WebClient with the GraphQL server’s base URL:

WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:8080/graphql")
.build();


Sending the Query: Send the query as a POST request using WebClient:

String query = "{ \"query\": \"query { users { id name email } }\" }";

String response = webClient.post()
.bodyValue(query)
.retrieve()
.bodyToMono(String.class)
.block();

This POST request sends the GraphQL query to the server, which returns the JSON response with the requested data.

3. Process the GraphQL Response

The GraphQL response is a JSON object containing the data key with the results. For instance:

{
"data": {
"users": [
{
"id": "1",
"name": "John Doe",
"email": "john.doe@example.com"
},
{
"id": "2",
"name": "Jane Smith",
"email": "jane.smith@example.com"
}
]
}
}

This response includes the data object which contains the array of users.

By understanding these steps and the role of the each component, we can effectively integrate the GraphQL service with a Java application.

Example: Setting Up a GraphQL Server Application with Spring Boot

This section provides a sample setup for a GraphQL server with Spring Boot.

Step 1: Create a Spring Boot Project

Create a new Spring Boot project with the following settings:

  • Name: graphql-server-demo
  • Type: Maven Project

Click on the Next button.

πŸ‘ Project Metadata

Step 2: Add the Dependencies

Add the following dependencies into the Spring Boot Project:

  • Spring Web
  • Spring Boot DevTools
  • Lombok
  • Spring Data JPA
  • MySQL Driver
  • Spring for GraphQL

Click on the Create button.

πŸ‘ Add Dependencies

Project Structure

After the project creation done, set up the project structure as shown in the below image:

πŸ‘ Project Folder Structure

Step 3: Configure Application Properties

Open the application.properties file and add the following MySQL, Hibernate and GraphQL configuration.

spring.application.name=graphql-server-demo
# MySQL Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=mypassword
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

# Show SQL queries in the console (Optional)
spring.jpa.show-sql=true

# GraphQL Configuration
graphql.servlet.mapping=/graphql
graphql.graphiql.enabled=true

Step 4: Define the GraphQL Schema

Define a GraphQL schema for queries in schema.graphqls:

type Query {
users: [User]
userById(id: ID!): User
}

type User {
id: ID!
name: String!
email: String!
}

Step 5: Create the data.sql file

We will now create the data.sql file to insert the default data into the database.

INSERT INTO user (name, email) VALUES ('John Doe', 'john.doe@example.com');
INSERT INTO user (name, email) VALUES ('Jane Smith', 'jane.smith@example.com');
INSERT INTO user (name, email) VALUES ('Alice Johnson', 'alice.johnson@example.com');
INSERT INTO user (name, email) VALUES ('Bob Brown', 'bob.brown@example.com');
INSERT INTO user (name, email) VALUES ('Charlie Davis', 'charlie.davis@example.com');

Step 6: Create the User Entity

Create a User class to represent user data:

Step 7: Create the UserRepository Interface

Step 8: Create the UserService Class

Step 9: Create the UserController Class

Step 10: Main class

No changes are required in the main class.

pom.xml File:

Step 11: Run the Application

Once the project is completed, we will run the application and it will start at port 8080.

πŸ‘ Server Application Running

Setting Up a GraphQL Client Application

Step 1: Create a new Spring Boot Project

Create a new Spring Boot project using IntelliJ IDEA, then choose the following options:

  • Name: graphql-client-demo
  • Language: Java
  • Type: Maven
  • Packaging: Jar

Click on the Next button.

πŸ‘ Client Application Metadata

Step 2: Add the Dependencies

Add the following dependencies into the Spring Boot project:

  • Spring Reactive Web
  • Lombok
  • Spring Boot DevTools

Click on the Create button.

πŸ‘ Add Dependencies

Project Structure

Once the project is created, set the file structure as shown in the below image:

πŸ‘ Folder Structure

Step 3: Configure Application Properties

Now, we will configure the properties in application.properties.

spring.application.name=graphql-client-demo
server.port=8081
graphql.service.url=http://localhost:8080/graphql

Step 4: Create the User Class

Step 5: Create the UserService Class

Step 6: Create the UserController class

Step 7: Main class

No changes are required in the main class.

pom.xml File:

Step 9: Run the Application

Once the project is completed, we will run the project and it will start at port 8081.

πŸ‘ Client Application Running

Conclusion

Integrating GraphQL with a Java application allows for the efficient data fetching and flexibility in the API communication. By using the WebClient in the Spring Boot Project, we can easily send the queries to the GraphQL service and parse the results into Java objects. This method is particularly useful for the microservices and applications that need to fetch nested or complex data structures.

Comment
Article Tags:

Explore