GraphQL is becoming a popular way to use APIs in modern web and mobile apps.
However, learning new things is always time-consuming and without getting your hands dirty, it’s very difficult to understand the nuances of a new technology.
So, we have put together a powerful and concise tutorial that will guide you through setting up a GraphQL backend and integration into your React app in the shortest time possible. This tutorial is light on opinions, so that once you get a hang of the fundamentals, you can go on and tailor your workflow.
Key topics and takeaways:
- GraphQL API with AWS AppSync
- Working with multiple environments
- Removing services
What will we be building?
We will build a basic real-time Restaurant CRUD app using authenticated GraphQL APIs. Click here to try the deployed version of the app to see what we’ll be building.
Will this tutorial teach React or GraphQL concepts as well?
No. The focus is to learn how to use AWS Amplify to build cloud-enabled, real-time web applications. If you are new to React or GraphQL, we recommend going through the official documentation and then coming back here.
What do I need to take this tutorial?
- Node >= v10.9.0
- NPM >= v6.9.0 packaged with Node.
Getting started - Creating the application
To get started, we first need to create a React project using the create-react-app boilerplate:
Let’s now install the AWS Amplify and AWS Amplify React bindings and try running the application:
If you have initialized the app with Typescript and see errors while using
aws-amplify-react, add aws-amplify-react.d.ts to src with:
Installing the AWS Amplify CLI and adding it to the project
To install the CLI:
Now we need to configure the CLI with our credentials:
If you’d like to see a video walkthrough of this process, click here
Here we'll walk you through the amplify configure setup. After you sign in to the AWS console, follow these steps:
- Specify the AWS region: ap-south-1 (Mumbai) <Select the region based on your location. Click here for reference>
- Specify the username of the new IAM user: amplify-app <Name of your app>
In the AWS Console, click Next: Permissions, Next: Tags, Next: Review, and Create User to create the new IAM user. Then, return to the command line and press Enter.
- Enter the credentials of the newly created user:
- Profile Name: default
To view the newly created IAM user, go to the dashboard. Also, make sure that your region matches your selection.
To add amplify to your project:
Answer the following questions:
- Enter a name for the project: amplify-app <Name of your app>
- Enter a name for the environment: dev <Name of your environment>
- Choose your default editor: Visual Studio Code <Your default editor>
- Source Directory Path: src
- Distribution Directory Path: build
- Build Command: npm run build (for macOS/Linux), npm.cmd run-script build (for Windows)
- Start Command: npm start (for macOS/Linux), npm.cmd run-script start (for Windows)
- Do you want to use an AWS profile: Yes
- Please choose the profile you want to use: default
Now, the AWS Amplify CLI has initialized a new project and you will see a new folder: amplify. This folder has files that hold your project configuration.
To add authentication:
When prompted, choose:
- Do you want to use default authentication and security configuration: Default configuration
- How do you want users to be able to sign in when using your Cognito User Pool: Username
- What attributes are required for signing up: Email
Now, let’s run the push command to create the cloud resources in our AWS account:
To quickly check your newly created Cognito User Pool, you can run
To access the AWS Cognito Console at any time, go to the dashboard. Also, ensure that your region is set correctly.
Now, our resources are created and we can start using them.
The first thing is to connect our React application to our new AWS Amplify project. To do this, reference the auto-generated aws-exports.js file that is now in our src folder.
To configure the app, open App.tsx and add the following code below the last import:
Now, we can start using our AWS services.
To add the Authentication flow to the UI, export the app component by wrapping it with the authenticator HOC:
Now, let’s run the app to check if an Authentication flow has been added before our App component is rendered.
This flow gives users the ability to sign up and sign in. To view any users that were created, go back to the Cognito dashboard. Alternatively, you can also use:
The withAuthenticator HOC is a really easy way to get up and running with authentication, but in a real-world application, we probably want more control over how our form looks and functions. We can use the aws-amplify/Auth class to do this. This class has more than 30 methods including signUp, signIn, confirmSignUp, confirmSignIn, and forgotPassword. These functions return a promise, so they need to be handled asynchronously.
Adding and Integrating the GraphQL API
To add GraphQL API, use the following command:
Answer the following questions:
- Please select from one of the below mentioned services: GraphQL
- Provide API name: RestaurantAPI
- Choose an authorization type for the API: API key
- Do you have an annotated GraphQL schema: No
- Do you want a guided schema creation: Yes
- What best describes your project: Single object with fields (e.g., “Todo” with ID, name, description)
- Do you want to edit the schema now: Yes
When prompted, update the schema to the following:
Next, let’s run the push command to create the cloud resources in our AWS account:
- Are you sure you want to continue: Yes
- Do you want to generate code for your newly created GraphQL API: Yes
- Choose the code generation language target: typescript
- Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.ts
- Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Yes
- Enter maximum statement depth [increase from default if your schema is deeply nested]: 2
- Enter the file name for the generated code: src/API.ts
Notice your GraphQL endpoint and API KEY. This step has created a new AWS AppSync API and generated the GraphQL queries, mutations, and subscriptions on your local. To check, see src/graphql or visit the AppSync dashboard. Alternatively, you can use:
Please select from one of the below mentioned services: GraphQL
Now, in the AppSync console, on the left side click on Queries. Execute the following mutation to create a restaurant in the API:
Now, let’s query for the restaurant:
We can even search / filter data when querying:
Now that the GraphQL API is created, we can begin interacting with it from our client application. Here is how we’ll add queries, mutations, and subscriptions:
Finally, we have our app ready. You can now sign-up,sign-in, add new restaurants, see real-time updates of newly added restaurants.
The hosting category enables you to deploy and host your app on AWS.
- Select the environment setup: DEV (S3 only with HTTP)
- hosting bucket name: <YOUR_BUCKET_NAME>
- index doc for the website: index.html
- error doc for the website: index.html
Now, everything is set up & we can publish it:
Working with multiple environments
You can create multiple environments for your application to create & test out new features without affecting the main environment which you are working on.
When you use an existing environment to create a new environment, you get a copy of the entire backend application stack (CloudFormation) for the current environment. When you make changes in the new environment, you are then able to test these new changes in the new environment & merge only the changes that have been made since the new environment was created.
Let's take a look at how to create a new environment. In this new environment, we'll add another field for the restaurant owner to the GraphQL Schema.
First, we'll initialize a new environment using amplify init:
- Do you want to use an existing environment: N
- Enter a name for the environment: apiupdate
- Do you want to use an AWS profile: Y
Once the new environment is initialized, we should be able to see some information about our environment setup by running:
Now, add the owner field to the GraphQL Schema in
Run the push command to create a new stack:
After testing it out, it can be merged into our original dev environment:
- Do you want to update code for your updated GraphQL API: Y
- Do you want to generate GraphQL statements: Y
If at any time, you would like to delete a service from your project & your account, you can do this by running the amplify remove command:
If you are unsure of what services you have enabled at any time, amplify status will give you the list of resources that are currently enabled in your app.
The sample code for this blog post with an end to end working app is available here.
Once you've worked through all the sections above, your app should now have all the capabilities of a modern app, and building GraphQL + React apps should now be easier and faster with Amplify.