Discuss how you would add a GraphQL API to an existing Spring Boot RESTful service.

Adding a GraphQL API to an existing Spring Boot REST service means layering a schema-driven query interface alongside the existing REST endpoints, typically using the spring-boot-starter-graphql module built on GraphQL Java.

Key Points: • Add the spring-boot-starter-graphql dependency, which brings in GraphQL Java and Spring's integration support. • Define the API contract in a schema file, conventionally src/main/resources/graphql/schema.graphqls, describing types, queries, and mutations. • Implement data fetchers as @Controller classes with @QueryMapping and @MutationMapping methods that delegate to existing services. • The GraphQL endpoint, by default /graphql, can coexist with existing REST controllers without conflict. • Test the API with tools like GraphiQL, Postman, or Spring's own GraphQL test client before rolling it out.

Example: An existing ProductService used by REST controllers is reused unchanged; a new @QueryMapping method named "product" calls the same service to resolve GraphQL queries, so no business logic is duplicated between the REST and GraphQL layers.

Code Example:

type Query {
    product(id: ID!): Product
}

type Product {
    id: ID!
    name: String!
    price: Float!
}
@Controller
public class ProductGraphQLController {

    private final ProductService productService;

    @QueryMapping
    public Product product(@Argument String id) {
        return productService.findById(id);
    }
}

Interview Tip: A concise interview answer is:

"I'd add spring-boot-starter-graphql, define the schema in a .graphqls file, and write data fetcher controllers with @QueryMapping and @MutationMapping that call into the same service layer the REST controllers already use. That way GraphQL and REST coexist without duplicating business logic."