Page updated Nov 21, 2023

Set up Amplify GraphQL API

Amplify's GraphQL API category allows you to build a secure, real-time GraphQL API backed by a database in minutes. Define your data model in a GraphQL schema and Amplify will deploy a GraphQL API powered by AWS AppSync, connect to a database powered by Amazon DynamoDB on your behalf. You can secure your API with authorization rules and scale to custom use cases with AWS Lambda.

Creating your first API and database table

Amplify's GraphQL API category can be deployed either using the Amplify CLI or using AWS Cloud Development Kit (CDK). The Amplify Command Line Interface (CLI) is a unified toolchain to create, integrate, and manage the AWS cloud services for your frontend app. The AWS CDK is an open-source Infrastructure-as-Code framework used to model and provision your AWS cloud application resources with familiar programming languages.

Pre-requisites:

First, set up your GraphQL API by running:

amplify add api
1amplify 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) ... Edit your schema at <...>/schema.graphql or place .graphql files in a directory at <...>/schema ✔ Do you want to edit the schema now? (Y/n) > yes Edit the file in your editor: <...>/schema.graphql ✅ Successfully added resource new locally
1? Select from one of the below mentioned services:
2> GraphQL
3? Here is the GraphQL API that we will create. Select a setting to edit or continue
4> Continue
5? Choose a schema template:
6> Single object with fields (e.g., “Todo” with ID, name, description)
7...
8Edit your schema at <...>/schema.graphql or place .graphql files in a directory at <...>/schema
9✔ Do you want to edit the schema now? (Y/n)
10> yes
11Edit the file in your editor: <...>/schema.graphql
12✅ Successfully added resource new locally

Accept the default values and your code editor should show a GraphQL schema for a Todo app with the following code:

# This "input" configures a global authorization rule to enable public access to # all models in this schema. Learn more about authorization rules here: https://docs.amplify.aws/cli/graphql/auth input AMPLIFY { globalAuthRule: AuthRule = { allow: public } } # FOR TESTING ONLY! type Todo @model { id: ID! name: String! description: String }
1# This "input" configures a global authorization rule to enable public access to
2# all models in this schema. Learn more about authorization rules here: https://docs.amplify.aws/cli/graphql/auth
3input AMPLIFY {
4 globalAuthRule: AuthRule = { allow: public }
5} # FOR TESTING ONLY!
6type Todo @model {
7 id: ID!
8 name: String!
9 description: String
10}

input AMPLIFY { globalAuthRule: AuthRule = { allow: public } } allows you to get started quickly without worrying about authorization rules. Review the Authorization rules section to setup the appropriate access control for your GraphQL API.

Every GraphQL type with the @model directive is automatically backed by a new DynamoDB database table and generates create, read, update, and delete GraphQL queries and mutations for you.

Now let's deploy your changes to the cloud:

Run the following command in your Terminal:

amplify push -y
1amplify push -y

That's it! Your API and database tables are set up.

Setup your app code

To connect your application to your API, we recommend to use the Amplify Library and auto-generated GraphQL client helper code. This gives you the ability to hit the ground running with sensible defaults that you can tweak as your use cases evolve for more optimization.

Install the Amplify Library

Use Amplify libraries to connect your app with your GraphQL endpoint.

Add the Amplify library to your app with npm:

npm install aws-amplify
1npm install aws-amplify

Configure the Amplify Library in your app code

As part of the amplify push deployment workflow, a new amplifyconfiguration.json file is generated for you. amplifyconfiguration.json is the client configuration file for the Amplify libraries, it includes your API endpoint URL, authentication information, and region.

In your app's entry point i.e. App.js in React, import and load the configuration file:

import { Amplify } from 'aws-amplify'; import { generateClient } from 'aws-amplify/api'; import config from './amplifyconfiguration.json'; Amplify.configure(config); const client = generateClient();
1import { Amplify } from 'aws-amplify';
2import { generateClient } from 'aws-amplify/api';
3import config from './amplifyconfiguration.json';
4Amplify.configure(config);
5
6const client = generateClient();

Generate GraphQL client helper code

As part of the amplify push deployment workflow, a new src/graphql/ folder is generated that contains client helper code for GraphQL queries, mutations, and subscriptions.

We'll use these files in the next step, to make create, read (list, get), update, and delete API requests in just a couple lines of code.

Add your first record

Next, let's try to query from the GraphQL API. Follow along the steps below to make a query from a React app:

import { generateClient } from 'aws-amplify/api'; import { createTodo, updateTodo, deleteTodo } from './graphql/mutations'; import { listTodos } from './graphql/queries';
1import { generateClient } from 'aws-amplify/api';
2import { createTodo, updateTodo, deleteTodo } from './graphql/mutations';
3import { listTodos } from './graphql/queries';

Then, create your first todo item with the a GraphQL API call:

const client = generateClient(); const result = await client.graphql({ query: createTodo, variables: { input: { name: 'My first todo!' } } });
1const client = generateClient();
2
3const result = await client.graphql({
4 query: createTodo,
5 variables: {
6 input: {
7 name: 'My first todo!'
8 }
9 }
10});

Query records from the table

Use the GraphQL query statement to list all todos in your app:

const result = await client.graphql({ query: listTodos }); console.log(result);
1const result = await client.graphql({ query: listTodos });
2console.log(result);

You should see the record created above: My first todo!.

Update the record

To update the record use the GraphQL update mutation:

const result = await client.graphql({ query: updateTodo, variables: { input: { id: '<...>', name: 'My first updated todo!' } } }); console.log(result);
1const result = await client.graphql({
2 query: updateTodo,
3 variables: {
4 input: {
5 id: '<...>',
6 name: 'My first updated todo!'
7 }
8 }
9});
10console.log(result);

The result should contain the updated value: My first updated todo!.

Delete a record

Let's clean up your database! Delete the todo by using the delete mutation:

const result = await client.graphql({ query: deleteTodo, variables: { input: { id: '<...>' } } }); console.log(result);
1const result = await client.graphql({
2 query: deleteTodo,
3 variables: {
4 input: {
5 id: '<...>'
6 }
7 }
8});
9console.log(result);

The result output should indicate to you that the record was successfully deleted!

Iterating on your data model using the GraphQL schema

If you want to update your API, open your project's amplify/backend/api/<api-name>/schema.graphql file (NOT the one in the amplify/backend/api/<api-name>/build folder) and edit it in your favorite code editor. You can compile the amplify/backend/api/<api-name>/schema.graphql file by running:

amplify api gql-compile
1amplify api gql-compile

and view the compiled schema output in backend/api/~apiname~/build/schema.graphql.

You can then push updated changes with:

amplify push
1amplify push

The following schema updates require replacement of the underlying DynamoDB table:

  1. Removing or renaming a model
  2. Modifying the primary key of a model
  3. Modifying a Local Secondary Index of a model (only applies to projects with secondaryKeyAsGSI turned off)

When trying to push a schema change with one or more of these updates you will see an error message explaining that you will lose ALL DATA in any table that requires replacement. To confirm you want to continue with the deployment, run:

amplify push --allow-destructive-graphql-schema-updates
1amplify push --allow-destructive-graphql-schema-updates

In general, this command should only be used during development.

If you are making a breaking change to a production API but you want to retain the data in the affected table(s), you can create a backup before running amplify push --allow-destructive-graphql-schema-updates

Rebuild GraphQL API

Rebuild should NEVER be used in a production environment!

When in development, sometimes test data gets in a bad state or you want to make many changes to your schema all at once. In these cases, you may wish to "rebuild" all of the tables backing your schema. To do this, run the following in your Terminal:

amplify rebuild api
1amplify rebuild api

This will recreate ALL of the tables backing models in your schema. ALL DATA in ALL TABLES will be deleted.

Next steps

Success! You've learned how to create a GraphQL API backed by a database table and also how to run queries and mutations from your app.

There's so much more to discover with Amplify's GraphQL API capabilities. Learn more about: