"Spring Boot and GraphQL: A Guide to Building Scalable APIs and Optimizing Data Fetching"

October 10, 2024

Introduction:

Spring boot is used to create a Rest service with scalable application. Spring boot provides in-built embedded tomcat server so, we don’t need to add the external server. Spring boot is built based on Spring MVC so, it is provide the MVC structure as well. 

The most valuable feature we don’t need to create any beans or other configuration based on xml file. Also we are able to make the spring boot application with microservice. War or Jar files can be directly deployed on the tomcat server. Basically spring boot provides to create the Rest end points. We are also creating the spring boot application with spring security, where spring security provides the authentication to prevent to access the rest services from the third party. The latest version of spring boot is 3.3.

Integrate GraphQL with Spring boot:

GraphQL stands for Graph “Query Language”. GraphQL is a query language and used to provide the requested data based on Rest service using spring boot. GraphQL provides the feature to fetch the data from multiple data sources with single Rest API call.

Using the GraphQL we don’t have to create the too many Rest services for every resource.  GraphQL provides one URL to get the requested data from different Rest services. Before GraphQL we have to create the too many APIs for every resource or we have to call the services based on request data. GraphQL returns the data in the JSON format.

Prerequisites to integration GraphQL in Spring boot:

  • Basic knowledge of Java and Spring boot.
  • Maven for dependency Management.
  • Postman tool for testing the Application.
  • JDK and IntelliJ or Eclipse installed on your system.

Implementation of GraphQL in Spring boot:

Step-1: Create the Spring boot application using spring initializer.
Link:
https://start.spring.io

After that import the maven project in the eclipse.

Structure of the Application:

Step-2 : Configure the Application properties
Open the application.properties file and add the MySQL and Hibernate Configuration.
Locate the file: src/main/resources

In above file we have specified the database connection URL, username and password. The database name is graphql_db.

Step-3: Create the GraphQL Schema:
File name: schema.graphqls
Location: src/main/resources/graphql

This is used for to defines the data structure and mutation and it is includes the add and retrieve operation.

Step-4: Create the data SQL file.
File name: data.sql

Location: src/main/resources

Step-5: Create a File Entity
Create a package name as com.graphql.entity and in this package create the new class name as File.

This is used to get the data and set the data as per the user request.

package com.graphql.model;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
 
import lombok.Getter;
import lombok.Setter;
 
@Entity
@Getter
@Setter
@Table(name = “files”)
public class Files {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String title;
    private String author;
public Files() {
}
public Files(int id, String title, String author) {
    this.id = id;
    this.title = title;
    this.author = author;
}

This is represent the database table name in the database. With Lombok annotation we don’t have to create the getter and setter. Lombok internally create the getter and setter.

Step-6: Create the FileRepository interface.

  • Create a new package name as com.graphql.repository and in this package create a FileRepository interface.
  • In this repository we have extended the JpaRepository to create a CRUD operation.
  • JpaRepository provide the in-built methods to create a CRUD operation.
  • CRUD stands for Create, Read, Update and D

package com.graphql.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.graphql.model.Files;

public interface FileRepository extends JpaRepository<Files, Integer> {

}

Step–7: Create the FileResolver Class

  • Create the FileResolver class in the src/main/java/com/graphql/resolver.
  • Annotate this class as a controller and add the method to get the file using id.
  • Annotate the FileRepository as autowired so, we don’t want to make or configure the bean. As @Autowired annotation is internally create the object and configure as a bean.
package com.graphql.resolver;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
 
import com.graphql.model.Files;
import com.graphql.repository.FileRepository;
 
 
@Controller
public class FileResolver {
 
@Autowired
private FileRepository fileRepository;
 
@QueryMapping
public Files getFileById (@Argument Integer id) {
return fileRepository.findById(id).orElse(null);
}
}

Step-8 Entry point(Main Class):

  • The main class, GraphqlWithSpringbootApplication is the enrty point of the spring boot application.
  • This class is annotated with @SpringBootApplication annotation.
  • @SpringBootApplication annotation is the combination of @EnableAutoConfiguration, @Configuration, and @ComponentScan annotation.
  • @EnableAutoConfiguration: The use of this annotation is the application will automatically configures the bean.
  • @Configuration: The use of this annotation is the Spring boot application will automatically configured.
  • @ComponentScan: The use of this annotation is that it is scan the root package and sub package classes an configure.
package com.graphql;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class GraphqlWithSpringbootApplication {
 
public static void main(String[] args) {
SpringApplication.run(GraphqlWithSpringbootApplication.class, args);
}
 
}

Step-9 Run the Application

Open the command prompt from your project root folder and add the below command.

1.mvn clean
2.mvn spring-boot:run

The application will run on port 8085 because we have configured the port in application.properties file.

Step-10 Test the Application

After successfully run the application enter below URL and GraphQL query in the postman.

Request and response from postman:

The endpoint graphql is the default endpoint. If you want to add the custom endpoint, then the put below property in the application.properties file.

Property: graphql.servlet.mapping=/custom-graphql

Get In Touch

"Share your ideas and get the best software service in the industry."

No comment

Leave a Reply

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