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
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
-
First step is to add the schema method, open
lesson.schema.graphql
found atserverside/src/main/resources/graphql/schemas/lesson.schema.graphql
and add the following to our query protected region calledAdd 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 thewhere
andorderBy
parameters for the sake of simplicity. -
Add a mapped method to our query resolver, open
LessonQueryResolver.java
found atserverside/src/main/java/lmsspring/graphql/resolvers/query/LessonQueryResolver.java
and add the following method in the protected region calledImport 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:
- Added security annotation at the top of the method
- Accepted page size and index for pagination
- Pulled user ID from the security context to be used in our filter
- Created a custom condition and parsed it to our service (here we are reusing the
isStarted
condition created for our REST API).
The only key difference is that we return the list of lessons rather than a response object.
-
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.
Was this article helpful?