GraphQL Integration with Spring Boot

Bharath ReddyBharath Reddy
3 min read

Introduction to GraphQL Integration with Spring Boot

As a student diving into the world of backend development, you might have encountered RESTful APIs as the standard way to build and consume web services. However, there's a new kid on the block that's gaining popularity for its flexibility and efficiency: GraphQL. In this article, we'll explore how to integrate GraphQL with Spring Boot, a powerful combination that can help you build more dynamic and efficient APIs.

What is GraphQL?

GraphQL is a query language for your API, developed by Facebook. Unlike REST, which has fixed endpoints and returns pre-defined data structures, GraphQL allows clients to request exactly the data they need. This reduces over-fetching and under-fetching of data and makes APIs more efficient and flexible.

Setting Up a Spring Boot Project

First, let's create a Spring Boot project. You can use Spring Initializr (https://start.spring.io/) to generate a basic project with the necessary dependencies. Select the following dependencies:

  • Spring Web

  • Spring Boot DevTools

  • GraphQL Spring Boot Starter

  • GraphQL Java Tools

Once you have the project set up, add the following dependencies to your pom.xml if they are not already included:

<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>
<dependency>
    <groupId>com.graphql-java-kickstart</groupId>
    <artifactId>graphql-java-tools</artifactId>
    <version>11.1.0</version>
</dependency>

Defining Your GraphQL Schema

A GraphQL schema defines the structure of the data that can be queried. Create a new file schema.graphqls in the src/main/resources directory:

type Query {
    studentById(id: ID!): Student
    allStudents: [Student]
}

type Student {
    id: ID
    name: String
    age: Int
    course: String
}

Implementing the Student Model

Create a simple Student model class in the model package:

package com.example.demo.model;

public class Student {
    private String id;
    private String name;
    private int age;
    private String course;

    // Constructors, getters, and setters
    public Student(String id, String name, int age, String course) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.course = course;
    }

    // Getters and setters
}

Creating the Student Repository

For simplicity, we'll create an in-memory repository. In a real-world application, this would interact with a database.

package com.example.demo.repository;

import com.example.demo.model.Student;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Repository
public class StudentRepository {
    private List<Student> students = new ArrayList<>();

    public StudentRepository() {
        students.add(new Student("1", "John Doe", 20, "Computer Science"));
        students.add(new Student("2", "Jane Smith", 22, "Mathematics"));
    }

    public Optional<Student> findById(String id) {
        return students.stream().filter(student -> student.getId().equals(id)).findFirst();
    }

    public List<Student> findAll() {
        return students;
    }
}

Creating GraphQL Resolvers

Resolvers are the heart of GraphQL and define how to fetch the data for each field in your schema. Create a StudentQueryResolver class:

package com.example.demo.resolver;

import com.coxautodev.graphql.tools.GraphQLQueryResolver;
import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
public class StudentQueryResolver implements GraphQLQueryResolver {

    @Autowired
    private StudentRepository studentRepository;

    public Optional<Student> studentById(String id) {
        return studentRepository.findById(id);
    }

    public List<Student> allStudents() {
        return studentRepository.findAll();
    }
}

Testing Your GraphQL API

With the application set up, you can now run it and test your GraphQL API. Spring Boot will automatically expose a GraphiQL interface at http://localhost:8080/graphiql where you can run your queries.

Here are a couple of example queries:

  1. Get a student by ID:
query {
    studentById(id: "1") {
        id
        name
        age
        course
    }
}
  1. Get all students:
query {
    allStudents {
        id
        name
        age
        course
    }
}

Conclusion

Integrating GraphQL with Spring Boot provides a powerful and flexible way to build APIs. By allowing clients to specify exactly what data they need, GraphQL can make your applications more efficient and responsive. As you continue your journey as a backend developer, mastering these tools will be a valuable addition to your skillset. Happy coding!

0
Subscribe to my newsletter

Read articles from Bharath Reddy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bharath Reddy
Bharath Reddy