Developer Docs

Custom GraphQL API with SpringBot

This article extends from what was covered in Custom REST API endpoint with SpringBot as such will rely some of the changes made in that article.

Setup

  1. To assist us we will be using the GraphiQL interface which can be found at http://localhost:8080/graphiql after logging into your application.

Adding the API method

  1. First step is to add the schema method, open lesson.schema.graphql found at serverside/src/main/resources/graphql/schemas/lesson.schema.graphql and add the following to our query protected region called Add any additional query definition here:
# % protected region % [Add any additional query definition here] on begin
lessonsStarted(pageIndex: Int = 0, pageSize: Int = 10): [Lesson!]!
# % protected region % [Add any additional query definition here] end

For this we are copying the signature from the lessons method, renaming it and removing the where and orderBy parameters for the sake of simplicity.

  1. Add a mapped method to our query resolver, open LessonQueryResolver.java found at serverside/src/main/java/lmsspring/graphql/resolvers/query/LessonQueryResolver.java and add the following method in the protected region called Import any additional class methods here:
@PreAuthorize("hasPermission('LessonEntity', 'read')")
public List<LessonEntity> lessonsStarted(
        int pageIndex,
        int pageSize
) {
    var securityContext = SecurityContextHolder.getContext().getAuthentication();
    UserEntity loggedInUser = null;
    if (securityContext != null) {
        loggedInUser = (UserEntity) securityContext.getPrincipal();
    }

    var isStarted = new Where();
    isStarted.setPath("isStarted");
    isStarted.setValue((loggedInUser != null) ? loggedInUser.getId().toString() : null);

    var lessons = lessonService.findSortedPageWithQuery(
            (pageIndex > 0) ? pageIndex - 1: pageIndex,
            pageSize,
            Collections.singletonList(
                    Collections.singletonList(isStarted)
            ),
            Sort.by("modified").descending()
    );
    return lessons;
}

This process is very similar to creating our REST controller in that we:

The only key difference is that we return the list of lessons rather than a response object.

  1. Testing this endpoint in GraphiQL gives us the following result:

Solution

Have a look at the custom-api branch to see the code solution.

Video

Our ‘How To: Build a custom API with REST and GRAPHQL’ video outlines the steps above.