Home United States USA — software Java and GraphQL: A Guide

Java and GraphQL: A Guide

194
0
SHARE

Learn how to use Java, Spring Boot, and JUnit 5 to build and test a GraphQL API.
Join the DZone community and get the full member experience. It is quite difficult to design REST APIs as they need to serve multiple clients efficiently. Each client has their own needs, and therefore requires different parameters around data filtering and searching, which is where a traditional rest API comes in. Clients can navigate the single version, picking and choosing the data they want. Developed by Facebook to overcome the shortcomings of REST API, GraphQL acts as a query language for APIs, as well as a runtime for fulfilling those queries with your extant data. When you provide a complete and clear description of the data in your API, clients can utilize that to ask for exactly what they need. When you expose your schema, the evolution of APIs becomes much easier. Clients can still navigate the schema to fit their needs, even if you add more fields and relations over time. In this article, I will be walking you through the process of using Java and Spring Boot to build a GraphQL API. In addition, I will also go through the steps to test your GraphQL API using Java’s most popular testing library: JUnit 5. If you would rather watch a video or follow along with the audio, you can watch this tutorial as a screencast. Let’s start with an initialized app by going to Spring Initializr and defining your app data as follows: You may also follow this link, it will take you to a pre-configured Spring Initializr page. Expand the downloaded package and add GraphQL SPQR as a dependency to your pom.xml: Then create a Food entity class: Notice that you are already using GraphQL SPQR (GraphQL Schema Publisher & Query Resolver, pronounced like speaker) annotations (i.e. @GraphQLQuery) on the entity. This is how it will know to expose those entities in the API. Create the respective repository: In GraphQL you can either define a query which will only load data, or define a mutation which will also change the underlying data that feeds the API. For this sample app, you will define the basic read, save and delete functionality for food entities. For that, create a service class: Notice that you are also able to define calculated properties to entities. In the above class, you declared the method isGood() as a property that can be queried for each food. You will see ahead that you can read it just like you read the food’s id and name fields. To initialize the app with sample data, add an ApplicationRunner bean definition in GraphqldemoApplication: Also, add the following line to application.

Continue reading...