When building modern APIs, especially for frontend-heavy applications, performance and flexibility are critical. REST APIs, while widely adopted, often return either too much or too little data, requiring multiple roundtrips or custom endpoints. That’s where GraphQL shines—allowing clients to query exactly what they need in a single request. In this post, we’ll explore how to build an efficient GraphQL API using Java, why it improves response speed for complex payloads, and walk through a step-by-step demo.
Why GraphQL?
- Precise payloads: Clients request only the fields they need.
- Reduces over-fetching/under-fetching: Unlike REST, no more generic response objects.
- Efficient rendering: Especially useful for UI components that depend on deeply nested data.
- Single endpoint, flexible queries: One endpoint, many possibilities.
Tech Stack
- Java 17+
- Spring Boot 3+
- graphql-java (https://www.graphql-java.com/)
- GraphQL Spring Boot Starter
- Gradle or Maven
Step-by-Step: Create a Sample GraphQL API in Java
1. Set Up Spring Boot Project
Use Spring Initializr with dependencies:
- Spring Web
- Spring Boot DevTools
- Spring Boot GraphQL
Or add to pom.xml (for Maven):
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>21.0</version>
</dependency>
2. Define Your GraphQL Schema
Create schema.graphqls in src/main/resources/graphql:
type Query {
bookById(id: ID!): Book
}
type Book {
id: ID
title: String
author: String
publishedYear: Int
}
3. Create Domain and Data
public class Book {
private String id;
private String title;
private String author;
private int publishedYear;
// Constructors, Getters, Setters
}
4. Create a Repository or Service
@Service
public class BookService {
private final Map<String, Book> bookStore = Map.of(
"1", new Book("1", "GraphQL in Action", "Sai", 2022),
"2", new Book("2", "Spring Boot Essentials", "Lee", 2023)
);
public Book getBookById(String id) {
return bookStore.get(id);
}
}
5. Create GraphQL Query Resolver
@Component
public class BookQueryResolver implements GraphQLQueryResolver {
private final BookService bookService;
public BookQueryResolver(BookService bookService) {
this.bookService = bookService;
}
public Book bookById(String id) {
return bookService.getBookById(id);
}
}
6. Test with GraphiQL
Run your app and open GraphiQL or Postman:
query {
bookById(id: "1") {
title
author
}
}
Performance Insights
- With GraphQL, clients don’t over-fetch nested or unused attributes, which reduces bandwidth.
- Especially beneficial in mobile/web apps where response time is critical.
- Backend services are optimized because resolvers run only for requested fields.
Final Thoughts
GraphQL gives you the power to shape responses around UI needs while maintaining backend efficiency. In Java, it integrates cleanly with Spring Boot, and once you get used to schema-first development, it’s incredibly productive.