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
}
}
- 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
}
}
- 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
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
- Click Create API button
- Under Select API type, select GraphQL APIs, under GraphQL API Data Source, select Start with a DynamoDB table and Click Next button
- Enter An API name (I have given BooksAPI for the API name)
- 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
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
- 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.
- Configure the remaining Fields aligning with Books Table of DynamoDB
- Under Additional settings, select Velocity Template Language (VTL), then click Next, review the information and then click Create API:
Now You can see the magic
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.
Here You can see the BooksAPI created
- Click Schema and You will be navigated to the view the Schema of BooksAPI
- Click Data sources to view the DynamoDB Books table Data source
- Click Queries in the left navigation pane and you'll be redirected to the Queries page for BooksAPI:
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
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.
Here You can see the Query result as data objects with all attributes as selected by the user on the left pane
Specifying only the title and author fields within items will return only those two fields:
Click Run Button and Select listBooksTables
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
}
}
The createbookstableinput
is 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.
The createBooksTable
mutation takes a createbookstableinput
argument 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
You can see the output on right pane
You can also see the item added on DynamoDB Console
Its Postman Time
Now Lets Connect to Postman Tool
To connect to postman tool we need some details from aws appsync console
- Click Settings
Scroll down and Copy API Key and paste to a notepad
- Now, Open Postman tool and Click
New
to create a request
We need to create an http request
- Select
GraphQL
and Proceed
- Paste the GraphQL endpoint from notepad here
- Click
Authorization
Select API Key from Dropdown
-
Provide the valid credentials
- Type
x-api-key
to the Key Field - Paste the apikey value copied from notepad
- Type
- 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
}
}
You should be able to see the item deleted from DynamoDB Console as well