Table of Contents
What is GraphQL?
GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. It was developed by Facebook and released in 2015. Unlike REST APIs, where you often have multiple endpoints returning fixed data structures, GraphQL allows clients to request exactly the data they need, making it more flexible and efficient.
Key Features of GraphQL
- Declarative Data Fetching: Clients specify exactly what data they need, which reduces over-fetching and under-fetching of data.
- Single Endpoint: All data is accessed via a single endpoint, unlike REST where each resource might have its own endpoint.
- Strongly Typed Schema: The schema defines the types and relationships in the API, making it self-documenting and easier to understand.
- Real-time Updates: GraphQL supports subscriptions, enabling real-time data updates.
- Introspection: GraphQL allows querying the schema itself to understand available queries and data types.
Implementing GraphQL in a Spring Boot Application
To implement GraphQL in a Spring Boot application, follow these steps:
Start by setting up a Spring Boot project. You can use Spring Initializr to generate the project. Include the following dependencies:
- Spring Boot Starter Web: For building RESTful web applications.
- GraphQL Spring Boot Starter: To add GraphQL support.
- GraphQL Java Tools: For easy GraphQL schema definition.
Add Dependencies
First, you need to add the necessary dependencies to your pom.xml
 (for Maven) or build.gradle
 (for Gradle) file.
For Maven:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>12.0.0</version> <!-- Check for the latest version -->
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>12.0.0</version> <!-- Check for the latest version -->
</dependency>
</dependencies>
For Gradle:
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'com.graphql-java-kickstart:graphql-spring-boot-starter:12.0.0'
implementation 'com.graphql-java-kickstart:graphql-java-tools:12.0.0'
Define the GraphQL Schema
GraphQL uses a schema to define the data types and relationships. Create a .graphqls
file in the src/main/resources
directory.
For example, create schema.graphqls
:
type Query {
getBookById(id: ID!): Book
}
type Book {
id: ID!
title: String!
author: String!
}
In this schema:
Query
is the root type for all queries.getBookById
is a query that returns aBook
based on its ID.Book
is a type with fieldsid
,title
, andauthor
.
Create the Data Model
Create a simple Java class to represent the Book
entity.
package com.learnspringbootonline.graphql.model;
public class Book {
private String id;
private String title;
private String author;
public Book(String id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
}
// Getters and Setters
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
}
Create the Service Layer
Create a service class to manage your data. For simplicity, we’ll use a static list of books.
package com.learnspringbootonline.graphql.service;
import com.learnspringbootonline.graphql.model.Book;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
@Service
public class BookService {
private List<Book> books = Arrays.asList(
new Book("1", "1984", "George Orwell"),
new Book("2", "To Kill a Mockingbird", "Harper Lee")
);
public Optional<Book> getBookById(String id) {
return books.stream().filter(book -> book.getId().equals(id)).findFirst();
}
}
Create the GraphQL Resolver
The resolver maps the GraphQL schema to the service layer. Create a resolver class for your queries.
package com.learnspringbootonline.graphql.resolver;
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
import com.learnspringbootonline.graphql.model.Book;
import com.learnspringbootonline.graphql.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BookQueryResolver implements GraphQLQueryResolver {
@Autowired
private BookService bookService;
public Book getBookById(String id) {
return bookService.getBookById(id).orElse(null);
}
}
Here, BookQueryResolver
implements GraphQLQueryResolver
and provides the logic for the getBookById
query defined in your schema.
Run and Test the Application
Run your Spring Boot application. Spring Boot will automatically expose a GraphQL endpoint at /graphql
.
You can test your GraphQL API using tools like Postman or by visiting http://localhost:8080/graphql
and sending a query:
{
getBookById(id: "1") {
id
title
author
}
}
This query will return:
{
"data": {
"getBookById": {
"id": "1",
"title": "1984",
"author": "George Orwell"
}
}
}
Conclusion
Implementing GraphQL in a Spring Boot application involves defining a schema, creating a resolver, and connecting it to your service layer. GraphQL provides a flexible and efficient way to interact with your APIs, allowing clients to request exactly the data they need. This can lead to more efficient data retrieval and reduced bandwidth usage compared to traditional REST APIs.
Explore our diverse collection of blogs covering a wide range of topics here.