GraphQL API with Spring Boot

David Kumar Jan 2026
3 tabs
type User {
    id: ID!
    name: String!
    email: String!
    posts: [Post!]!
    createdAt: String!
}

type Post {
    id: ID!
    title: String!
    content: String!
    author: User!
    comments: [Comment!]!
    createdAt: String!
}

type Comment {
    id: ID!
    content: String!
    author: User!
    post: Post!
    createdAt: String!
}

type Query {
    user(id: ID!): User
    users(page: Int = 0, size: Int = 10): [User!]!
    post(id: ID!): Post
    posts(userId: ID): [Post!]!
}

type Mutation {
    createUser(name: String!, email: String!, password: String!): User!
    updateUser(id: ID!, name: String, email: String): User!
    deleteUser(id: ID!): Boolean!
    createPost(userId: ID!, title: String!, content: String!): Post!
}

type Subscription {
    postCreated: Post!
}
3 files · graphql, java Explain with highlit

GraphQL provides flexible APIs where clients specify exact data requirements. Spring for GraphQL integrates GraphQL Java with Spring Boot. Schema-first approach defines types in .graphqls files. Resolvers map schema fields to Java methods using @QueryMapping, @MutationMapping. DataLoader prevents N+1 queries through batching. GraphQL enables fetching related data in single request, reducing over-fetching and under-fetching. Subscriptions support real-time updates via WebSocket. Error handling uses DataFetcherExceptionHandler. Pagination uses cursor-based approach. GraphQL excels for complex data requirements, mobile apps, and evolving APIs. The self-documenting schema simplifies frontend development. Spring's annotation-based approach makes GraphQL accessible to Java developers familiar with REST.