Create GraphQL API in Spring Boot example

In this blog, we will learn graphql API in spring boot and see graphql schema, query, etc.

we are going to implement graphql in the existing spring boot project that we have created in the previous spring-boot-JPA-integration-with-SQLite.

GraphQL API tutorial in Spring boot 

What is GraphQL?

GraphQL is a query language for API not specific to any database or framework developed by Facebook, GraphQL client uses graphQL query( specific which fields we are looking for in response) to fetch data from the server.

In GraphQL, the client can get all details in a single request instead of multiple calls to the backend like REST API.


Graphql Maven dependency

we need to add the below dependency in the pom.xml file which provides support for creating graphQL API in spring boot. 


<dependency>
	<groupId>com.graphql-java</groupId>
	<artifactId>graphql-spring-boot-starter</artifactId>
	<version>5.0.2</version>
</dependency>
<dependency>
	<groupId>com.graphql-java</groupId>
	<artifactId>graphql-java-tools</artifactId>
	<version>5.2.4</version>
</dependency>
<!-- GraphiQL -->
<dependency>
	<groupId>com.graphql-java</groupId>
	<artifactId>graphiql-spring-boot-starter</artifactId>
	<version>5.0.2</version>
</dependency>

By default, the GraphQL Service will be accessible on /graphql URL and will accept POST requests with the GraphQL Payload. If required, you can modify this endpoint in our application.properties file.


Create GraphQl Schema

First, we need to create a graphql schema that contains the graphql query and object type (similar to class) that return in the response.

graphQL API tutorial schema diagram

The graphql server exposes this schema to the graphql client describing the available query and structure of object data (class and their field) based on schema the client creates a query and sends it to the server for execution.

create a schema.graphqls file inside the src/main/resource folder.


schema {
  query: Query
}

type Query {
  getAllEmployee: [Employee]
  getEmployeeById(id: Int): Employee
}

type Employee {
  id: ID
  name: String
  jobTitle: String
  mobileNo: String
  joinedDate: String
  gender: String
  department: Department
  project: Project
}

type Department {
  id: ID
  name: String
}

type Project {
  id: ID
  name: String
}

Here the Employee, Department, and Project are graphql object types. The [Employee] means an array of employee objects.

The getAllEmployee and getEmployeeById are queries the client use to fetch object data from the graphql server.

we can have several separate schema files to organize the schemes, e.g. we can have employee.graphqls, project.graphqls, etc.

There can be only one query and mutation type describing all operations, if there are separate schema files each containing its own query and mutation then use extend keyword so all queries and mutation are added together.


Create a JPA repository

let's create a JPA repository to get employee details from the SQLite database.


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.graphql.model.Employee;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {

}

Create Query Resolver

Now create a class GraphQLService that implements GraphQLQueryResolver, this class contains the actual implementation of a query defined in the graphql schema. 

The query name defined in schema and method name must be the same. 


import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
import com.example.graphql.model.Employee;
import com.example.graphql.repo.EmployeeRepository;

@Component
public class GraphQLService implements GraphQLQueryResolver {

	@Autowired
	private EmployeeRepository employeeRepository;

	public List<Employee> getAllEmployee() {
		return employeeRepository.findAll();
	}

	public Employee getEmployeeById(int id) {
		return employeeRepository.findById(id).orElse(null);
	}
}

The getAllEmployee returns all employee details from the database and getEmployeeById returns specific employee details using employee id.

Add @Component annotation to the class else spring boot will not be available find our query resolver while scanning which will cause a 404 error when we try to access /graphql endpoint.


Test using GraphIQl 

Once the spring boot application is up and running, we can access the /graphql endpoint.

To test graphQL we can use GraphIQL tools which will be available on http://localhost:8080/graphiql when the application is running.

Using GraphIQL, we can send queries to the server and check responses. the right side contains the scheme we have defined as documentation showing query, mutation, subscription. The left side contains the query we will be sending.

sending getAllEmployee graphQL query.

graphQL query tutorial

sending getEmployeeById graphQL query.


Spring boot graphQL tutorial query

In the above query, we are sending id directly (hardcoded) so each time we need to update the query, the parameter can be sent in dynamically like JSON request body without touching the query like below.

Graphql tutorial diagram query spring boot

The main feature of GraphQL is we can get all responses in a single request see below image we have sent both queries together in a single request. 

Graphql tutorial diagram query spring boot


GraphQL schema visualizer

Sometimes we want to see the visual presentation of the graphQL scheme to show the team. By using voyager we can visualize the graphQL schema, add the below dependency in the pom.xml file and run the application.

we can access the voyager in http://localhost:8080/voyager URL.


<dependency>
	<groupId>com.graphql-java-kickstart</groupId>
	<artifactId>voyager-spring-boot-starter</artifactId>
	<version>7.0.1</version>
	<scope>runtime</scope>
</dependency>

Below is the visualization of our graphQL schema.

grpahQL api voyager tutorial


Post a Comment

Previous Post Next Post

Recent Posts

Facebook