GraphQL has become a go-to API implementation for developers looking to take advantage of features liketype safety, network efficiency, real-time data with subscriptions & more.
Building, managing, & deploying your own GraphQL server can be tedious & time consuming, especially for developers new to the technology that may want to quickly get a real-world, secure & scalable GraphQL API up and running without having to learn how to create it from scratch (as well as spend the time learning best practices around API design & authorization).
In this post we’ll learn how to use AWS AppSync, a fully managed GraphQL service, to create a serverless GraphQL API. AWS AppSync allows developers to quickly create serverless, scalable & secure GraphQL APIs.
We’ll be using AWS Amplify to create the AppSync service & connect to it from our React application. AWS Amplify is a CLI & Client toolchain that allows developers to create AWS services from their front-end environment & connect to them from the client-side applications.
The app that we will be building is a restaurant tracker app that will allow us to keep up with all of the restaurants we would like to visit as well as store information about each restaurant. We’ll use React as the front-end for the application.
The AWS Amplify CLI is the tool that we will be using to create the AWS AppSync API. This CLI allows us to create & deploy AWS services directly from the command line. The services that we will be creating are AWS AppSync for the API layer & Amazon Cognito for the authentication provider.
Users will be able to sign up for an account, sign in to the account, create a restaurant, & query for only the restaurants that the user created.
First, we’ll create the React application that we’ll be using to connect to our API. To do so, we’ll use Create React App:
Once the app is created, we’ll change into the new directory & install aws-amplify:
The next thing we need to do is install & configure the AWS Amplify CLI. To do so, we’ll use npm:
Once the CLI is installed, we’ll need to configure it to use an IAM user from our AWS account
If you’d like a video walkthrough of how to install & configure the AWS Amplify CLI, click here.
Now that the CLI is installed & configured, we can initialize a new Amplify project in our React application. From the inside your React application, run the following command:
Here, you will be prompted with questions about your application configuration. You can choose your default text editor and the defaults for all of the other options.
Once the project has been initialized, we can go ahead and add an an API & authentication to our app. To do so, we’ll first add authentication.
To add the AWS AppSync api, we can run the following command:
Choose an authorization type for the API: API key
Do you have an annotated GraphQL schema: N
Do you want a guided schema creation: Y
What best describes your project: Single object with fields
Update the schema to this & save the file:
Next, we’ll run the push command to create the services in our account:
Now, you’ll be prompted for the following:
Do you want to generate code for your newly created GraphQL API? Y
Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/*/.js
Do you want to generate/update all possible GraphQL operations – queries, mutations and subscriptions: Y
Once the push is complete, the AWS AppSync service have been successfully created in our account.
What exactly has been created? If you notice, in the above schema definition, we have an @model directive on the schema type definition. This is part of the Amplify GraphQL Transform library.
The library will recognize this directive & automcatically expand the schema into additional schema that is typically necessary for a robust API, including queries, mutations, subscriptions, resolvers & a data source (Amazon DynamoDB). Everything you need to get up & running is now set up for you using this directive.
If at any time you would like to view the services that have been created in your Amplify configuration, you can run
To view the AWS AppSync console & see the API that was just created, click here. To view the Cognito user pool that was just created, click here.
Make sure that you are in the same region in which you created your resource by viewing the region in the top right corner of the AWS console.
Now that the API has been created, we can go to the AWS AppSync console & begin testing it out! To do so, visit the AWS AppSync console (be sure you are in the correct region), & click on the API name you just created.
In the left hand menu, you will see links for your data source, settings, schema, & queries. Feel free to click around here & explore.
What we’d like to do next though is execute mutations & queries against the API. In the left hand menu, click on Queries & try out the following mutation in the query editor:
Creating a query in the AWS Console
Create a couple of mutations & then we’ll query for them using the following query:
This query should return an array of restaurans showing the id, name & description for each item created.
You may be wondering where the ID comes from, since all we did was pass in a name & description. The ids are automatically generated by the service (in the resolver mapping template) so you don’t have to pass them in. If you’d like to view the mapping template for any resolver, click on Schema in the left menu, look for the resolver you’d like to view in the resolvers panel on the right.
Now that the services are created, we can wire them up with our React application & begin interacting with them.
The first thing we’ll do is configure the application with our Amplify resources. To configure the React application, open index.js & add the following three lines of code:
Next, open App.js. Here, we’ll query for the restaurants & display them in our app. To do so, we’ll need to do 5 things:
First, we’ll take care of our imports:
Next, in the class definition, we’ll go ahead & create the state & initialize the query in componentDidMount lifecycle method:
In componentDidMount we fetch the data from the AppSync API by using the API class, calling API.graphql passing in the graphqlOperation helper & the query definition. We the store the data in the restaurants array after it has returned from the array & reset the state.
Now, the data is stored in the state & we can render it to our screen. Let’s update the render method to show the restaurant data in our UI:
For the final gist of all of the code for this component, check out this link.
Now, we should be able to run the app & see the queried data rendered to our screen:
Now that we know how to query for data, let’s look at how to submit mutations & create new items in our API. To do so, we’ll create a form with an input that will create new items in our API & display them to the screen.
To do so, we’ll need to do 5 things:
First, we’ll import the mutation:
Next, we’ll update the state to hold the restaurant name & description:
Now, we’ll create the two methods we’ll need to handle user input & call the API to create a restaurant:
createRestaurant method we do 5 things:
Finally, we’ll create the UI for the form fields & button to call the
For a final gist for all of the code for this component, click here.
Now, we should be able to run the app and create new restaurants from the React application:
As I mentioned in the introduction, one of the most powerful features of GraphQL are real-time data with subscriptions.
Subscriptions push data from the server to the clients that choose to listen to the real time data coming from the server. We can subscribe to the creation of a new item, in our case the creation of a new restaurant, & get notified of the creation of the item as well as receive the item data in the subscription callback.
To implement subscriptions, we need to do three things:
When the subscription fires, we do 3 things:
In this tutorial we’ve walked through all of the typical GraphQL operations you would use in a real-world application. We’ve also built & deployed a real-world GraphQL API that will automatically scale for you as your application scales.
The only data source we’ve looked at so far is DynamoDB, but AWS AppSync also supports other data sources out of the box (including Amazon ElasticSearch, AWS Lambda, & http resolvers). If you’re interested in learning more about using other data sources, check out the documentation here.
This content was originally published here.