Quickly Set Up a GraphQL API for DynamoDB CRUD operations with Just a Few Clicks Using AWS AppSync

Nandini Rajaram - Nov 10 - - Dev Community

What is GraphQL?

GraphQL is a query language for APIs and a runtime for executing those queries. It was developed by Facebook in 2012 and released publicly in 2015

Why GraphQL?

Instead of an API where you hit a URL and accept whatever data comes back, GraphQL allows you to ask for specific data, giving clients more control over what information is sent.

A Practical Example

For example, you may say, "Hey REST API, give me the titles of the books available on Cloud Tuner Online Library," in order to retrieve data from the Rest API. The way this works is that you contact a specific endpoint, or URL, in our instance the Cloud Tuner Online Library, and that URL controls the data that returns. When you retrieve a URL using the REST API, it usually returns something in the form of a Javascript object or JSON with data on it. This leads to either repeated journeys (requests) to satisfy different queries, or undesired data that we have to sift through to retrieve our needed data. But GraphQL isn't like that.
Rather than using an API where you click a URL and consent

Queries and Mutations

Query
In GraphQL, a query is used to fetch specific data from the server. You define the fields you want to retrieve, and the server returns only that data. Let's look at a typical GraphQL query example and break it down.

Example Query
Imagine you want to get a list of books, their titles, authors, and publication years from the "Cloud Tuner Online Library." Here's how you would write that query in GraphQL:

 query {
  books {
    title
    author {
      name
    }
    publicationYear
  }
}
Enter fullscreen mode Exit fullscreen mode
  • query: This is the keyword that tells GraphQL you’re making a read operation to fetch data.
  • books: This is the field you're querying. In this case, it refers to the list of books available in the library.
  • title, author, publicationYear: These are the specific fields you want to retrieve for each book.
  • author { name }: This is an example of requesting a nested field. Here, you're asking for the name field inside the author object associated with each book.

Mutation
A mutation in GraphQL is used to modify or create data on the server. While queries are used to fetch data, mutations are used for actions like adding, updating, or deleting records.

Example Mutation
Let’s say you want to add a new book to the "Cloud Tuner Online Library." Here’s how you would write a GraphQL mutation to do that:

mutation {
  addBook(title: "New Book Title", author: "New Author", publicationYear: 2024) {
    id
    title
    author
    publicationYear
  }
}
Enter fullscreen mode Exit fullscreen mode
  • mutation: This keyword indicates that you're making a write operation, meaning you're modifying data on the server.
  • addBook: This is the mutation operation name. It corresponds to a mutation defined on the server that handles the logic for adding a book to the library.
  • Arguments: Inside the parentheses, you provide the necessary inputs for the mutation, such as the title, author, and publicationYear of the book.
  • Fields: After the mutation is successful, you can request specific fields to be returned. Here, we're asking for the id, title, author, and publicationYear of the newly added book.

CRUD APIs with AWS AppSync and DynamoDB

AWS AppSync is a fully managed, pay-per-use GraphQL service that allows developers to create and test web and mobile applications utilizing real-time data. AppSync allows developers to construct an API that is available via a single endpoint and uses GraphQL as a unified query language. AppSync manages data requests and responses, as well as connections to one or more data sources, such as AWS Lambda, AWS DynamoDB, and HTTP APIs.

Amazon DynamoDB is a cloud-based NoSQL database that is ideal for anyone looking for a dependable and completely managed NoSQL solution. DynamoDB is intended to allow automated storage scaling with low latency. It is especially beneficial when your application must read and store large volumes of data while maintaining speed and dependability (Amazon uses database replicas in three separate Availability Zones). Amazon DynamoDB is completely managed. Simply select an AWS region and define the necessary indexes for each table you will create, and Amazon will handle the rest.

Here We will work with the AWS AppSync interface via the AWS console to build a GraphQL API backed by DynamoDB datasource

Prerequisites

  • Books Table in DynamoDB with Items added.

Please refer the below link for creating the DynamoDB table
Cook a recipe with AWS: Dynamo DB Table

Image description

AWS AppSync has the capability to instantly generate a GraphQL schema and link resolvers to an already-existing data source, like an AWS DynamoDB database. Developers can first concentrate on database architecture rather than the GraphQL schema thanks to this functionality. For users who are unfamiliar with GraphQL, the automatically produced schema and resolvers can also serve as a foundation that can be readily built upon.

  • Navigate to Appsync Console

Image description

  • Click Create API button

Image description

  • Under Select API type, select GraphQL APIs, under GraphQL API Data Source, select Start with a DynamoDB table and Click Next button

Image description

  • Enter An API name (I have given BooksAPI for the API name)

Image description

  • In the Import DynamoDB Table form, configure the following, then click Next button
    • Region: Select US-WEST-2 from the drop-down menu
    • Table name: Select BooksTable
    • Create or use an existing role: You can create an new role A role with following permission will be created for you

Image description

Role grants AppSync the permissions it needs to perform create, read, update, and delete (CRUD) operations on data stored in DynamoDB.

  • Click next button after filling the details

Image description

  • Now On the Model information step, configure the following:
    • Model Name - Iam giving the name as BooksTable
    • The Fields section can be populated with the Table Fields, including details such as the Field Type, whether the Field is an array, and if the Field is mandatory. These details should align with the DynamoDB Books Table. The Primary Key Field is autopopulated.

Image description

  • Configure the remaining Fields aligning with Books Table of DynamoDB

Image description

  • Under Additional settings, select Velocity Template Language (VTL), then click Next, review the information and then click Create API:

Image description

Image description

Now You can see the magic

Image description

Using this Book model, AppSync will create a GraphQL schema that includes queries, mutations, and subscriptions to handle the basic CRUD operations for your API( Creation of items into DynamoDB, Reading items from DynamoDB,Updating Item in DynamoDB and Deletion of items from DynamoDB)
AppSync will also generate the necessary resolvers and mapping templates to manage the data flow between the client and the BooksTable data source.


Image description

Here You can see the BooksAPI created

  • Click Schema and You will be navigated to the view the Schema of BooksAPI

Image description

  • Click Data sources to view the DynamoDB Books table Data source

Image description

  • Click Queries in the left navigation pane and you'll be redirected to the Queries page for BooksAPI:

Image description

Here You will be able to see the Query editor which can be used for writing, validating, and testing GraphQL operations, including queries, mutations, and subscriptions.

Fetching The Items from BooksTable of DynamoDB using GraphQL Query

Click Run Button and Select listBooksTables

Image description

This will execute the listBooksTables query which will fetch all items from BooksTable of DynamoDB as Data Objects in JSON Format

A data object is returned that includes an items array. This array consists of all three books stored in BooksTable. Each item has all available fields returned in the output, which is declared in the listBooks query, within items.

Image description

Here You can see the Query result as data objects with all attributes as selected by the user on the left pane

Image description


Specifying only the title and author fields within items will return only those two fields:

Image description

Click Run Button and Select listBooksTables

Image description


Adding an Item to the Books Table of DynamoDB Using GraphQL Mutatation

To add a new Book item to the table, replace the JSON object defined in the Query Variables section with the following:

{
  "createbookstableinput": {
    "title": "ChatGPT for Dummies",
    "id": "fBGILBdSSSAw2aDMQo8GaS4w1ozyChos",
    "author": "ChatGPT",
    "releaseDate": "01-01-2023",
    "genre": "Education",
    "pageCount": 500,
    "price": 25
  }
}
Enter fullscreen mode Exit fullscreen mode

The createbookstableinputis an input type defined in the API schema. During the creation process, AppSync automatically generates these input definitions for you. More examples of input types will be available as you explore the generated schema.

Image description

The createBooksTable mutation takes a createbookstableinputargument and uses the DynamoDB PutItem action to store the new book in the BooksTable. After the operation completes, it returns the newly created object.

Click Run Button and Select createBooksTable

Image description

You can see the output on right pane

Image description

You can also see the item added on DynamoDB Console

Image description


Its Postman Time

Image description

Now Lets Connect to Postman Tool

To connect to postman tool we need some details from aws appsync console

  • Click Settings

Image description

  • Copy the GraphQL endpoint and paste to a notepad
    Image description

  • Scroll down and Copy API Key and paste to a notepad

Image description

  • Now, Open Postman tool and Click Newto create a request

Image description

We need to create an http request

  • Select GraphQLand Proceed

Image description

  • Paste the GraphQL endpoint from notepad here

Image description

  • Click Authorization

Image description

  • Select API Key from Dropdown

  • Provide the valid credentials

    • Type x-api-key to the Key Field
    • Paste the apikey value copied from notepad

Image description

  • Navigate to Query Tab
  • Copy the below Query Mutation and paste in Query Section and Click Query Button

mutation MyMutation {
  deleteBooksTable(input: {title: "The Mannequin in the Mirror"}) {
    id
  }
}
Enter fullscreen mode Exit fullscreen mode

Image description

You should be able to see the item deleted from DynamoDB Console as well

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .