Spring Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Introduction

In this article, we'll explore AWS AppSync with Spring Boot. AWS AppSync is a fully-managed, enterprise-level GraphQL service with real-time data synchronization and offline programming features.

2. Setup AWS AppSync

First, we need to have an active AWS account. Once that is taken care of, we can search for AppSync from the AWS console. Then we'll click the Getting Started with AppSync link.

2.1. Create AppSync API

Following the quick start instructions to create our API, we'll use the Event App sample project. Then click Start to name and create the app:

This will bring us to our AppSync app console. Now let's take a look at our GraphQL model.

2.2. GraphQL Event Model

GraphQL uses a schema to define what data is available to clients and how to interact with the GraphQL server. The schema contains queries, mutations, and a variety of declared types.

For simplicity, let's take a look at part of the default AWS AppSync GraphQL schema, our Event model:

type Event {
  id: ID!
  name: String
  where: String
  when: String
  description: String
  # Paginate through all comments belonging to an individual post.
  comments(limit: Int, nextToken: String): CommentConnection
}

Event is a declared type with some String fields and a CommentConnection type. Notice the exclamation point on the ID field. This means it is a required/non-null field.

This should be enough to understand the basics of our schema. However, for more information, head over to the GraphQL site.

3. Spring Boot

Now that we've set up everything on the AWS side, let's look at our Spring Boot client application.

3.1. Maven Dependencies

To access our API, we will be using the Spring Boot Starter WebFlux library for access to WebClient, Spring's new alternative to RestTemplate:

    <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-webflux</artifactId> 
    </dependency>

Check out our article on WebClient for more information.

3.2. GraphQL Client

To make a request to our API, we'll start by creating our RequestBodySpec using the WebClient builder, providing the AWS AppSync API URL and API key:

WebClient.RequestBodySpec requestBodySpec = WebClient
    .builder()
    .baseUrl(apiUrl)
    .defaultHeader("x-api-key", apiKey)
    .build()
    .method(HttpMethod.POST)
    .uri("/graphql");

Don't forget the API key header, x-api-key. The API key authenticates to our AppSync app.

4. Working With GraphQL Types

4.1. Queries

Setting up our query involves adding it to a query element in the message body:

Map<String, Object> requestBody = new HashMap<>();
requestBody.put("query", "query ListEvents {" 
  + " listEvents {"
  + "   items {"
  + "     id"
  + "     name"
  + "     where"
  + "     when"
  + "     description"
  + "   }"
  + " }"
  + "}");

Using our requestBody, let's invoke our WebClient to retrieve the response body:

WebClient.ResponseSpec response = requestBodySpec
    .body(BodyInserters.fromValue(requestBody))
    .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
    .acceptCharset(StandardCharsets.UTF_8)
    .retrieve();

Finally, we can get the body as a String:

String bodyString = response.bodyToMono(String.class).block();
assertNotNull(bodyString);
assertTrue(bodyString.contains("My First Event"));

4.2. Mutations

GraphQL allows for updating and deleting data through the use of mutations. Mutations modify the server-side data as needed and follow a similar syntax to queries.

Let's add a new event with an add mutation query:

String queryString = "mutation add {"
  + "    createEvent("
  + "        name:\"My added GraphQL event\""
  + "        where:\"Day 2\""
  + "        when:\"Saturday night\""
  + "        description:\"Studying GraphQL\""
  + "    ){"
  + "        id"
  + "        name"
  + "        description"
  + "    }"
  + "}";
 
requestBody.put("query", queryString);

One of the greatest advantages of AppSync, and of GraphQL in general, is that one endpoint URL provides all CRUD functionality across the entire schema.

We can reuse the same WebClient to add, update, and delete data.  We will simply get a new response based on the callback in the query or mutation.

assertNotNull(bodyString);
assertTrue(bodyString.contains("My added GraphQL event"));
assertFalse(bodyString.contains("where"));

5. Conclusion

In this article, we looked at how quickly we can set up a GraphQL app with AWS AppSync and access it with a Spring Boot client.

AppSync provides developers with a powerful GraphQL API through a single endpoint. For more information, have a look at our tutorial on creating a GraphQL Spring Boot server.

And, as always, the code is available over on GitHub.

Spring bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!