Design a site like this with WordPress.com
Get started

[19] – Implementing Microservices using GraphQL, AWS AppSync and DynamoDB

If you have been following this blog, you are aware that I am enamored by this new kid on the block called GraphQL. It has the potential to bring much needed transformation to the REST programming model that is the current gold standard for implementing APIs

Earlier, we had created microservices using REST APIs. In this blog, we will look at creating the same microservices using GraphQL

GraphQL is implemented on both client-side and server-side. Client-side operations consists of asking something to be done (like Get data or Change data in DB) and those requests are fulfilled by a GraphQL server. So, for using GraphQL, we need to setup a GraphQL server and use client-side libraries to communicate with server. There are many vendors who provide these components, one of them being Apollo

However, we do not want to undergo the process of setting up one or many GraphQL servers and nursing them. So, we go for an option that any modern (and lazy) cloud architect will choose. Using GraphQL Managed services offered by a cloud vendor. That is where AWS AppSync comes into picture.

What is AWS AppSync

The official definition is:

AppSync is a managed service that uses GraphQL to make it easy for applications to get exactly the data they need.

With AppSync, you can build scalable applications, including those requiring real-time updates, on a range of data sources such as NoSQL data stores, relational databases, HTTP APIs, and your custom data sources with AWS Lambda. For mobile and web apps, AppSync additionally provides local data access when devices go offline, and data synchronization with customizable conflict resolution, when they are back online.

Hence, we will use this hosted GraphQL service to create our Books catalog microservices and data will be persisted in AWS DynamoDB NoSQL database.

Note: Since GraphQL is a new technology, if you are a beginner, it is advised to read fundamentals of GrahpQL here before continuing.

Previously, we had implemented the following operations for our book catalog REST API

Operation HTTP Method REST API Path
Add book to catalog POST /books
Delete a book DELETE /books/{id}
Get a book GET /books/{id}
List all books in catalog GET /books
Update a book PUT /books/{id}

We shall see how the same can be achieved using GraphQL

Setup Table in AWS DynamoDB

Let’s start with creating a table which our books catalog microservices will use for storing data.

Head over to your AWS Console and open DynamoDb service and click Create Table

Let’s name our table books and specify id as the primary key.

Now, uncheck the box named Use default settings under Table Settings, since we don’t want to accept default settings.

As soon as you uncheck, it will expand to show you more options

Then scroll a bit further down and Uncheck Read capacity and Write capacity check boxes.

Also set values as 1 for both, as shown below.

Then click Create button at bottom. After a while, you will see your table created.

This completes creation of table.

Now let’s add some sample data to it. Click on table name and then click Items tab.

Then click Create Item button

Click the drop-down on top left corner and select Text from it. Then paste below data and click Save.

Repeat the same steps to add another record.

That completes the work on DynamoDB.

AWS AppSync Setup

Now lets move on to setting AppSync. Most of the work now will be done here.

Open Aws console and search for AppSync and open the home page of AppSync.

I have some API’s already created and hence the image shows count of 4 above i.e. API(4). Please ignore it.

Now click Create API button

Select Build from scratch in above screen and click Start button

Let’s give name as books-api and click Create button

You should be seen your API landing page, as shown above.

Congrats! your API is created. Now let’s call it a day and have some beer, Shall we? 😊

Nah….AWS is good, but it cannot yet read your mind (operating word being Yet here)

You are welcome to take a refreshment break if you want, because things will get quite technical from this point onwards.

Schema Creation

The first thing to do in GraphQL is define a Schema. Schema encapsulates all the operations available in GraphQL along with their data types.

The two main operations which are going to be using are

  1. Query (equivalent to GET methods in REST)
  2. Mutation (substitutes for PATCH, PUT, DELETE & POST methods in REST)

So basically, Query is used for reading data and all the other operation that changes the state of your stored data are done using Mutation.

The main object of our API is Book. This is called Type in GraphQL. So, lets define the properties it

The exclamation (!) after text String means this field is mandatory.

Now let’s create our first operation which will be to query all books present in DynamoDb database.

In order to do that, we must first mention it in Schema., as shown below

Now let’s add the operation as a Query

This query, when executed, is expected to return an array of type Book

Now, click Edit Schema button on our landing page and paste the code on left-side box under Schema heading.

Then paste above code into left-side box with heading Schema

Click Save Schema button on top-right side.  If it is successful, you should see the message as below

Connecting Schema to Database

Next step is to connect our schema to DynamoDb database. For that, click Data Sources on left side menu.

Then click Create data source button

Give name as BooksTable and select other values as shown above. Then click Create button down below

This completes connecting our AppSync API to database.

Implementing Query

Now let’s implement our listBooks function. Click on Schemas from left menu.

Then under the heading Resolvers, scroll to get the Query section where you can see listBooks method.

Click Attach button and you will be taken to another screen.

Select BooksTable from Data source name drop-down.

Then in right side of request mapping template, click the drop-down Get item by id and select List items

Then remove all the comments and just keep the request and response mapping template as above.

Scroll up and click Save Resolver

This completes implementation of listBooks function.

Resolvers are the runtime pipes that take instruction from AppSync to backend (DynamoDB in this case) and bring back the data.

Request and Response mapping template are places where you can write logic or connect front-end items to backend even if it has different names. So in your query you can have text Description but in database, you store values under name Descr.

This are written in a different language called Apache Velocity Language.

However, we are not doing anything complex right now. All we are saying in request mapping template is to Scan a table and bring back all data. In response mapping template, we are saying send all data we go as-it-is to AppSync query.

Now if you go back to Resolver, it will show as below

Executing Query

Well, now its time to see the fruits of our labour. So, let’s do this.

Click on Queries menu item on left side and you will see an empty query page, as below

Type below query in it and click Orange (Play/Execute) button

And Bingo……..you should see two books returned from our DynamoDb database

Congratulation!. You have, for the first time in life, created a GraphQL API.

You don’t believe this is still an API? Ok, Let’s check something out.

Click on Settings menu option on left side and you should see a page as below

Yes. You got it. THIS is the URL to call your API. You can give this URL to any front-end developer and they will be able to use this GraphQL API as they use REST API. You are welcome 😊

This completes creating of a listBooks  operation using GraphQL API. Although it may not seem that big a deal, understand that you have taken your first baby step into the Future of APIs.

Let’s hope that this small step may become a giant leap in your API and Microservices based architectural journey

Happy Clouding!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: