Spring Controller vs RestController GraphQL

77 Views Asked by At

I have the following question: why are the GraphQL Controllers not annotated as a RestController in the spring? I followed the official guide from spring and only the Controllers annotation is used. However, if we look at the Response it's a JSON. My understanding is that:
@Controller annotation is typically used in UI-based applications where the response is generally an HTML page. @RestController can return data directly in the response body, typically in JSON or XML format.

@Controller
public class BookController {
    @QueryMapping
    public Book bookById(@Argument String id) {
        return Book.getById(id);
    }

    @SchemaMapping
    public Author author(Book book) {
        return Author.getById(book.authorId());
    }
}
1

There are 1 best solutions below

0
Brian Clozel On

The @RestController annotation is a combination of @Controller and @ResponseBody, a shortcut if you will. @Controller marks a class as a @Component (so considered as a bean during scanning) that has a specific role for web applications: the Spring infrastructure will look for mapping annotations on methods and use those to register handlers.

Spring for GraphQL project chose to reuse the @Controller signal for detecting handlers for GraphQL APIs. You can perfectly annotate a controller with @Controller and some of its methods with @GetMapping and @ResponseBody, others with @QueryMapping only. @RestController will also work, the only difference is that all @RequestMapping methods in the controller will expect to use the return value as the response body.

In the case of GraphQL, this makes no difference as there is no HTML view support and the values returned from methods are always expected to be contributed to the GraphQL response.