Getting Started with AWS

Build a React Application

Create a simple web application using AWS Amplify

Module 4: Add a GraphQL API and Database

In this module you will use the Amplify CLI and libraries to configure and add a GraphQL API to your app.

Introduction

Now that we've created and configured the app with Authentication, let's add an API.

In this module, you will add an API to your app using the Amplify CLI and libraries. The API you will be creating is a GraphQL API that leverages AWS AppSync (a managed GraphQL service) which is backed by Amazon DynamoDB (a NoSQL database). (For an introduction to GraphQL, visit this page.)

The app we will be building will be a Notes app that will allow users to create, delete, and list notes. This example will give you a good idea how to build many popular types of CRUD+L (create, read, update, delete, and list) applications.

What You Will Learn

  • Create and deploy a GraphQL API
  • Write front-end code to interact with the API

Key Concepts

API – Provides a programming interface that allows communication and interactions between multiple software intermediaries.

GraphQL – A query language and server-side API implementation based on a typed representation of your application. This API representation is declared using a schema based on the GraphQL type system. (To learn more about GraphQL, visit this page.)

 Time to Complete

15 minutes

 Services Used

Implementation

  • Create a GraphQL API and database

    a. Add a GraphQL API to your app by running the the following command from the root of your app directory:

    amplify add api
    
    ? Please select from one of the below mentioned services: GraphQL
    ? Provide API name: notesapp
    ? Choose the default authorization type for the API: API Key
    ? Enter a description for the API key: demo
    ? After how many days from now the API key should expire: 7 (or your preferred expiration)
    ? Do you want to configure advanced settings for the GraphQL API: No, I am done.
    ? 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
    ? Do you want to edit the schema now? Yes

    b. Open the GraphQL schema in your text editor: amplify/backend/api/myapi/schema.graphql.

    Update the file with the following schema:

    type Note @model {
      id: ID!
      name: String!
      description: String
    }
    

    c. Save the file. Then go back to the command line and hit enter to complete the API configuration step.

  • Deploy the API

    Now that the API has been configured locally it is time to deploy it. To do so, run the Amplify push command:

    amplify push --y

    This will do 3 things:

    1. Create the AppSync API
    2. Create a DynamoDB table
    3. Create the local GraphQL operations in a folder located at src/graphql that you can use to query the API

    To view the GraphQL API in your account at any time, run the following command:

    amplify console api
    
    > Choose GraphQL
    

    To view the Amplify app in your account at any time, run the following command:

    amplify console
  • Write front-end code to interact with the API

    Now that the back end has been deployed, let's write some code to allow users to create, list, and delete notes.

    Update src/App.js with the following code:

    import React, { useState, useEffect } from 'react';
    import './App.css';
    import { API } from 'aws-amplify';
    import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react';
    import { listNotes } from './graphql/queries';
    import { createNote as createNoteMutation, deleteNote as deleteNoteMutation } from './graphql/mutations';
    
    const initialFormState = { name: '', description: '' }
    
    function App() {
      const [notes, setNotes] = useState([]);
      const [formData, setFormData] = useState(initialFormState);
    
      useEffect(() => {
        fetchNotes();
      }, []);
    
      async function fetchNotes() {
        const apiData = await API.graphql({ query: listNotes });
        setNotes(apiData.data.listNotes.items);
      }
    
      async function createNote() {
        if (!formData.name || !formData.description) return;
        await API.graphql({ query: createNoteMutation, variables: { input: formData } });
        setNotes([ ...notes, formData ]);
        setFormData(initialFormState);
      }
    
      async function deleteNote({ id }) {
        const newNotesArray = notes.filter(note => note.id !== id);
        setNotes(newNotesArray);
        await API.graphql({ query: deleteNoteMutation, variables: { input: { id } }});
      }
    
      return (
        <div className="App">
          <h1>My Notes App</h1>
          <input
            onChange={e => setFormData({ ...formData, 'name': e.target.value})}
            placeholder="Note name"
            value={formData.name}
          />
          <input
            onChange={e => setFormData({ ...formData, 'description': e.target.value})}
            placeholder="Note description"
            value={formData.description}
          />
          <button onClick={createNote}>Create Note</button>
          <div style={{marginBottom: 30}}>
            {
              notes.map(note => (
                <div key={note.id || note.name}>
                  <h2>{note.name}</h2>
                  <p>{note.description}</p>
                  <button onClick={() => deleteNote(note)}>Delete note</button>
                </div>
              ))
            }
          </div>
          <AmplifySignOut />
        </div>
      );
    }
    
    export default withAuthenticator(App);
    

    There are 3 main functions in our app:

    1. fetchNotes - This function uses the API class to send a query to the GraphQL API and retrieve a list of notes.
    2. createNote - This function also uses the API class to send a mutation to the GraphQL API, the main difference is that in this function we are passing in the variables needed for a GraphQL mutation so that we can create a new note with the form data.
    3. deleteNote - Like createNote, this function is sending a GraphQL mutation along with some variables, but instead of creating a note we are deleting a note.
  • Run the app

    To test out the app, run the start command:

    npm start

Conclusion

You have now created a Notes app! Using AWS Amplify, you added a GraphQL API and configured create, read, and delete functionality in your app. In the next module, we'll add a storage service to your app.

Was this module helpful?

Thank you
Please let us know what you liked.
Sorry to disappoint you
Is something out-of-date, confusing or inaccurate? Please help us improve this tutorial by providing feedback.