Page updated Feb 7, 2024

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:

1amplify add api
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:

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/react/build-a-backend/graphqlapi/customize-authorization-rules/
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.

The Amplify GraphQL API CDK construct is currently only available for TypeScript but we're launching support soon for additional languages. Follow @AWSAmplify on X/Twitter to be amongst the first to be notified.

Pre-requisites:

In your CDK app's project root directory, install the GraphQL API construct dependencies:

1npm install @aws-amplify/graphql-api-construct

Next, go to your stack and import the Amplify GraphQL CDK construct and create your new Amplify GraphQL API:

1import {
2 AmplifyGraphqlApi,
3 AmplifyGraphqlDefinition
4} from '@aws-amplify/graphql-api-construct';
5
6export class BackendStack extends cdk.Stack {
7 constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
8 super(scope, id, props);
9
10 const amplifyApi = new AmplifyGraphqlApi(this, 'AmplifyCdkGraphQlApi', {
11 definition: AmplifyGraphqlDefinition.fromFiles(
12 path.join(__dirname, 'schema.graphql')
13 ),
14 authorizationModes: {
15 defaultAuthorizationMode: 'API_KEY',
16 apiKeyConfig: {
17 expires: cdk.Duration.days(30)
18 }
19 }
20 });
21 }
22}

Then create your GraphQL schema where you describe your data model. Create a new file called schema.graphql in your stack's folder with the following code:

1type Todo @model @auth(rules: [{ allow: public }]) {
2 id: ID!
3 name: String!
4 description: String
5}

@auth(rules: [{ allow: public }] designates that anyone authenticated with an API key can create, read, update, and delete "Todo" records.

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:

1amplify push -y

Run the following command in your Terminal:

1cdk deploy

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:

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:

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

As part of the cdk deploy deployment workflow, the CLI prints API endpoint, authentication information, and region into the Terminal. It should look something like this:

1✨ Deployment time: 62.86s
2
3Outputs:
4BackendStack.amplifyApiModelSchemaS3Uri = s3://.../model-schema.graphql
5BackendStack.awsAppsyncApiEndpoint = https://wy5mtp7jzfctxc5w5pzkcoktbi.appsync-api.us-east-1.amazonaws.com/graphql
6BackendStack.awsAppsyncApiId = YOUR_API_ID_VALUE_HERE
7BackendStack.awsAppsyncApiKey = da2-XXXX
8BackendStack.awsAppsyncAuthenticationType = API_KEY
9BackendStack.awsAppsyncRegion = us-east-1

We'll use this information to configure the Amplify libraries in your application code. In your app's entry point i.e. App.js in React, import and configure the Amplify libraries using the printed outputs:

1import { Amplify } from 'aws-amplify';
2
3Amplify.configure({
4 API: {
5 GraphQL: {
6 endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
7 region: 'us-east-1',
8 defaultAuthMode: 'apiKey',
9 apiKey: 'da2-xxxxxxxxxxxxxxxxxxxxxxxxxx'
10 }
11 }
12});

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.

After you deployed your API, you can optionally generate GraphQL client helper code. We'll use this code in the next step, to make create, read (list, get), update, and delete API requests in just a couple lines of code.

For this part, you first need to add code generation to your app code's repository with the following npx command in your Terminal from your app code root directory:

1npx @aws-amplify/cli codegen add --apiId <YOUR_API_ID> --region <YOUR_API_REGION>

Then you can generate GraphQL client code, every time your API schema changes using the following command:

1npx @aws-amplify/cli codegen

At this point, you should see a new src/graphql/ folder that contains client helper code for GraphQL queries, mutations, and subscriptions.

For Flutter, Android, and Swift client code generation, refer to JavaScript, Android, Swift, and Flutter client code generation.

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:

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:

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:

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:

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:

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:

1amplify api gql-compile

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

You can then push updated changes with:

1amplify push

If you want to update your API, open the schema.graphql file in your CDK project and edit it in your favorite code editor. You can then push updated changes with:

1cdk deploy

After deployment, make sure that your authentication settings are still correct and regenerate the GraphQL client helper code by re-running the following command in your Terminal:

1npx @aws-amplify/cli codegen

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:

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:

1amplify rebuild api
1cdk destroy
2cdk deploy

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: