Şuayb's BlogŞuayb's Blog
Home
Categories
Games
MediumAboutContact
Language
Theme
    1. Blog
    2. Programming
    3. Building APIs with Spring for GraphQL

Building APIs with Spring for GraphQL

PublishedDecember 15, 2024
UpdatedDecember 16, 2024
Reading time3 min read
JavaKotlinGraphQLSpring Boot
XLinkedInFacebook
Building APIs with Spring for GraphQL

Loading likes...

Spring for GraphQL simplifies the development of GraphQL APIs by integrating with Spring Boot. This guide demonstrates how to create a GraphQL API using Java and Kotlin, with examples for schema definition, query handling, and dependency injection.


Last updatedDecember 16, 2024

Total viewsLoading hits...

Previous articleGin - First ApplicationNext articleInput Validation in REST APIs
Şuayb Şimşek

Written by

Şuayb Şimşek

Backend-focused fullstack developer sharing practical notes on Spring Boot, security, microservices, and cloud-native architecture.

Expertise

  • Spring Boot
  • Go
  • Microservices
  • Next.js
  • Cloud Native

Connect

GitHubLinkedInMedium

Related posts

Spring Boot GraphQL JWE Authentication
Programming

Spring Boot GraphQL JWE Authentication

Learn how to secure your Spring Boot GraphQL APIs with stateless encrypted JWTs (JWE) while persisting user identities and roles in a JPA-backed database.

May 17, 20256 min read
JavaKotlinSpring BootSecurityJWTJWEGraphQL
Spring Boot Configuration Properties
Programming

Spring Boot Configuration Properties

Learn how to use @ConfigurationProperties for type-safe configuration, validate settings with @Validated, and manage environment-specific values with profile-specific application-{profile}.yml files.

February 4, 20263 min read
JavaKotlinSpring BootConfiguration
Spring Boot JWE Authentication with JPA
Programming

Spring Boot JWE Authentication with JPA

Learn how to use stateless encrypted JWTs (JWE) to secure your Spring Boot APIs while persisting user identities and roles in a JPA-backed database.

May 11, 20254 min read
JavaKotlinSpring BootSecurityJWTJWEJPA

About

Articles on Spring Boot, microservices, security, and more.

ContactStart here

Latest posts

  • Captain Tsubasa 2: World Fighters
  • Captain Tsubasa: Rise of New Champions
  • Spring Boot Configuration Properties
  • Spring Boot GraphQL JWE Authentication
  • Spring Boot JWE Authentication with JPA

Top topics

JavaKotlinSpring BootJWEJWTMicroservice

Subscribe

Get practical backend + fullstack notes when new articles are published.

Social

© 2024-2026 Şuayb's Blog. All rights reserved.

🌟 Why Use GraphQL?

GraphQL allows clients to request specific data, reducing over-fetching and under-fetching compared to REST. It also supports strong typing and facilitates efficient data fetching, making it a popular choice for modern APIs.


📋 Prerequisites

📋 Ensure you have the following:

  • ☕ Java Development Kit (JDK) 17+
  • 📦 Maven or Gradle installed
  • 🔤 A Java IDE (e.g., IntelliJ IDEA, Eclipse)

🛠️ Step 1: Add Dependencies

Include the following dependencies in your project to enable Spring for GraphQL.

Maven:

XMLpom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-graphql</artifactId>
</dependency>

Gradle:

GROOVYbuild.gradle
implementation 'org.springframework.boot:spring-boot-starter-graphql'

🛠️ Step 2: Define the GraphQL Schema

Create a schema file named schema.graphqls under the src/main/resources/graphql directory.

GRAPHQLschema.graphqls
type Query {
  getUser(id: ID!): User
  getUsers: [User]
}

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

🛠️ Step 3: Implement the Data Model and Services

Define the data model and service layer for handling queries.


🛠️ Step 4: Implement GraphQL Controllers

Controllers handle GraphQL queries and mutations. Use the @Controller annotation in Spring for GraphQL.


▶️ Running the Application

Run the application using the following commands:

Spring Boot (Java/Kotlin): Run the application with either stack to confirm the baseline setup is working before deeper tests.

BASH
./mvnw spring-boot:run

Access the GraphQL Playground at http://localhost:8080/graphiql to test your API.


🧪 Testing the GraphQL API

Here are some example queries to test your API:

  • Fetch a user by ID:
GRAPHQLquery.graphql
query {
  getUser(id: "1") {
    id
    name
    email
  }
}
  • Fetch all users:
GRAPHQLquery.graphql
query {
  getUsers {
    id
    name
    email
  }
}

🏁 Conclusion

You now have a practical Building APIs with Spring for GraphQL implementation with a clear, production-friendly Spring Boot structure. As a next step, adapt configuration and tests to your own domain, then validate behavior under realistic traffic and failure scenarios.

Entity

JAVAUser.java
package com.example.demo.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String id;
    private String name;
    private String email;
}

Service

JAVAUserService.java
package com.example.demo.service;

import com.example.demo.model.User;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class UserService {

    private final Map<String, User> userData = Stream.of(
        new User("1", "Alice", "alice@example.com"),
        new User("2", "Bob", "bob@example.com")
    ).collect(Collectors.toMap(User::getId, user -> user));

    public User getUser(String id) {
        return userData.get(id);
    }

    public List<User> getUsers() {
        return List.copyOf(userData.values());
    }
}

Entity

KOTLINUser.kt
package com.example.demo.model

data class User(
    val id: String,
    val name: String,
    val email: String
)

Service

KOTLINUserService.kt
package com.example.demo.service

import com.example.demo.model.User
import org.springframework.stereotype.Service

@Service
class UserService {

    private val userData = mapOf(
        "1" to User("1", "Alice", "alice@example.com"),
        "2" to User("2", "Bob", "bob@example.com")
    )

    fun getUser(id: String): User? = userData[id]

    fun getUsers(): List<User> = userData.values.toList()
}
JAVAUserController.java
package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;

import java.util.List;

@Controller
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @QueryMapping
    public User getUser(String id) {
        return userService.getUser(id);
    }

    @QueryMapping
    public List<User> getUsers() {
        return userService.getUsers();
    }
}

KOTLINUserController.kt
package com.example.demo.controller

import com.example.demo.model.User
import com.example.demo.service.UserService
import org.springframework.graphql.data.method.annotation.QueryMapping
import org.springframework.stereotype.Controller

@Controller
class UserController(
    private val userService: UserService
) {

    @QueryMapping
    fun getUser(id: String): User? = userService.getUser(id)

    @QueryMapping
    fun getUsers(): List<User> = userService.getUsers()
}