Getting Started with AWS

Build a Full-Stack 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

Overview

Now that we have 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 uses AWS AppSync (a managed GraphQL service) which is backed by Amazon DynamoDB (a NoSQL database). (For an introduction to GraphQL, see the GraphQL website.)

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 of how to build many popular types of CRUD+L (create, read, update, delete, and list) applications.

What you will accomplish

In this module, you will:
  • Create and deploy a GraphQL API
  • Write frontend 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.

 Time to complete

15 minutes

 Services used

Implementation

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

    amplify add api
    
    ? Select from one of the below mentioned services: GraphQL
    ? Here is the GraphQL API that we will create. Select a setting to edit or continue: Continue
    ? Choose a schema template: Single object with fields (e.g., "Todo" with ID, name, description)
    ? Do you want to edit the schema now? (Y/n) yes

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

    Update the file with the following schema:

    type Note @model @auth(rules: [ { allow: public } ] ){
      id: ID!
      name: String!
      description: String
    }

    c. Save the file.

  • 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 three things:

    1. Create the AWS 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 and then select GraphQL API in the left navigation pane:

    amplify console api
    
    > Choose GraphQL
    

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

    amplify console
    ? Which site do you want to open? AWS console
  • Now that the backend 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 "@aws-amplify/ui-react/styles.css";
    import { API } from "aws-amplify";
    import {
      Button,
      Flex,
      Heading,
      Text,
      TextField,
      View,
      withAuthenticator,
    } from "@aws-amplify/ui-react";
    import { listNotes } from "./graphql/queries";
    import {
      createNote as createNoteMutation,
      deleteNote as deleteNoteMutation,
    } from "./graphql/mutations";
    
    const App = ({ signOut }) => {
      const [notes, setNotes] = useState([]);
    
      useEffect(() => {
        fetchNotes();
      }, []);
    
      async function fetchNotes() {
        const apiData = await API.graphql({ query: listNotes });
        const notesFromAPI = apiData.data.listNotes.items;
        setNotes(notesFromAPI);
      }
    
      async function createNote(event) {
        event.preventDefault();
        const form = new FormData(event.target);
        const data = {
          name: form.get("name"),
          description: form.get("description"),
        };
        await API.graphql({
          query: createNoteMutation,
          variables: { input: data },
        });
        fetchNotes();
        event.target.reset();
      }
    
      async function deleteNote({ id }) {
        const newNotes = notes.filter((note) => note.id !== id);
        setNotes(newNotes);
        await API.graphql({
          query: deleteNoteMutation,
          variables: { input: { id } },
        });
      }
    
      return (
        <View className="App">
          <Heading level={1}>My Notes App</Heading>
          <View as="form" margin="3rem 0" onSubmit={createNote}>
            <Flex direction="row" justifyContent="center">
              <TextField
                name="name"
                placeholder="Note Name"
                label="Note Name"
                labelHidden
                variation="quiet"
                required
              />
              <TextField
                name="description"
                placeholder="Note Description"
                label="Note Description"
                labelHidden
                variation="quiet"
                required
              />
              <Button type="submit" variation="primary">
                Create Note
              </Button>
            </Flex>
          </View>
          <Heading level={2}>Current Notes</Heading>
          <View margin="3rem 0">
            {notes.map((note) => (
              <Flex
                key={note.id || note.name}
                direction="row"
                justifyContent="center"
                alignItems="center"
              >
                <Text as="strong" fontWeight={700}>
                  {note.name}
                </Text>
                <Text as="span">{note.description}</Text>
                <Button variation="link" onClick={() => deleteNote(note)}>
                  Delete note
                </Button>
              </Flex>
            ))}
          </View>
          <Button onClick={signOut}>Sign Out</Button>
        </View>
      );
    };
    
    export default withAuthenticator(App);

    Our app has three main functions:

    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.
  • 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 will add a storage service to your app.

Was this page helpful?