GraphQL with Spring Boot

METEHAN KARA
3 min readOct 7, 2024

--

What is GraphQL?

GraphQL is an open-source data query and manipulation language for APIs, developed by Facebook in 2012. Unlike REST, which exposes multiple endpoints, GraphQL allows clients to request exactly the data they need via a single endpoint, minimizing over-fetching and under-fetching.

Usage Scenarios

  1. Client-Specific Queries: When different clients (mobile apps, web apps) require different sets of data from the server.
  2. Efficient Data Fetching: For applications where fetching data from multiple sources in a single request is critical.
  3. Microservices Integration: When combining data from multiple microservices into a single API response is needed.

Benefits

  1. Exact Data Fetching: Clients can request precisely the data they need, improving efficiency and reducing network overhead.
  2. Single API Endpoint: Unlike REST, GraphQL uses a single endpoint, simplifying the API structure.
  3. Strongly-Typed Schema: GraphQL enforces a strict schema definition, improving API robustness and developer experience.
  4. Versionless API: With its flexible query structure, you can evolve APIs without introducing breaking changes or versioning.

Dockerfile for Running GraphQL

FROM openjdk:17-jdk-slim
WORKDIR /app
COPY target/graphql-spring-boot.jar /app/graphql-spring-boot.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "graphql-spring-boot.jar"]

How to Implement GraphQL with Spring Boot

  1. Add Dependencies: First, add the required dependencies to your pom.xml.
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>11.1.0</version>
</dependency>

<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>11.1.0</version>
</dependency>

2. Create a GraphQL Schema: Place your .graphqls schema file in src/main/resources/graphql/ folder.

type Query {
getUser(id: ID!): User
}

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

3. Implement the Resolver: Create a resolver class that maps GraphQL queries to Java methods.

@Component
public class UserResolver implements GraphQLQueryResolver {

public User getUser(Long id) {
return new User(id, "John Doe", "john.doe@example.com");
}
}

Sample Code with Scenario

1. Query Example: Fetching a User by ID

You can query a user with specific fields using GraphQL.

GraphQL Query:

query {
getUser(id: 1) {
id
name
}
}

Response:

{
"data": {
"getUser": {
"id": 1,
"name": "John Doe"
}
}
}

2. Mutation Example: Creating a New User

GraphQL Schema for Mutation:

type Mutation {
createUser(name: String!, email: String!): User
}

Resolver Implementation:

@Component
public class UserMutationResolver implements GraphQLMutationResolver {

public User createUser(String name, String email) {
// Logic to save user
return new User(1L, name, email);
}
}

GraphQL Mutation Query:

mutation {
createUser(name: "Jane Doe", email: "jane.doe@example.com") {
id
name
email
}
}

Response:

{
"data": {
"createUser": {
"id": 1,
"name": "Jane Doe",
"email": "jane.doe@example.com"
}
}
}

3. Paginated Query Example: Fetching Multiple Users

GraphQL Schema:

type Query {
getUsers(page: Int, size: Int): [User]
}

Resolver Implementation:

@Component
public class UserResolver implements GraphQLQueryResolver {

public List<User> getUsers(int page, int size) {
// Logic to fetch users with pagination
return userService.findAll(page, size);
}
}

GraphQL Query:

query {
getUsers(page: 1, size: 5) {
id
name
}
}

Response:

{
"data": {
"getUsers": [
{ "id": 1, "name": "John Doe" },
{ "id": 2, "name": "Jane Doe" }
]
}
}

Summary

GraphQL is a powerful alternative to REST, allowing clients to define exactly what data they need. This enables efficient data fetching, reduces network load, and improves developer experience. By using GraphQL in a Spring Boot application, you can expose a flexible API that grows with your application needs. With Docker, you can containerize your application and run it in any environment.

Implementing GraphQL in Spring Boot requires setting up dependencies, defining a GraphQL schema, and creating resolver methods for queries and mutations. By utilizing features such as mutations and paginated queries, your GraphQL API can become a dynamic and performant service layer for any modern application.

--

--