Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 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:

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)
...
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

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/react/build-a-backend/graphqlapi/customize-authorization-rules/
input AMPLIFY {
globalAuthRule: AuthRule = { allow: public }
} # FOR TESTING ONLY!
type Todo @model {
id: ID!
name: String!
description: String
}

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:

npm 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:

import {
AmplifyGraphqlApi,
AmplifyGraphqlDefinition
} from '@aws-amplify/graphql-api-construct';
export class BackendStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const amplifyApi = new AmplifyGraphqlApi(this, 'AmplifyCdkGraphQlApi', {
definition: AmplifyGraphqlDefinition.fromFiles(
path.join(__dirname, 'schema.graphql')
),
authorizationModes: {
defaultAuthorizationMode: 'API_KEY',
apiKeyConfig: {
expires: cdk.Duration.days(30)
}
}
});
}
}

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:

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

@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:

amplify push -y

Run the following command in your Terminal:

cdk 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:

npm 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();

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:

✨ Deployment time: 62.86s
Outputs:
BackendStack.amplifyApiModelSchemaS3Uri = s3://.../model-schema.graphql
BackendStack.awsAppsyncApiEndpoint = https://wy5mtp7jzfctxc5w5pzkcoktbi.appsync-api.us-east-1.amazonaws.com/graphql
BackendStack.awsAppsyncApiId = YOUR_API_ID_VALUE_HERE
BackendStack.awsAppsyncApiKey = da2-XXXX
BackendStack.awsAppsyncAuthenticationType = API_KEY
BackendStack.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:

import { Amplify } from 'aws-amplify';
Amplify.configure({
API: {
GraphQL: {
endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
region: 'us-east-1',
defaultAuthMode: 'apiKey',
apiKey: 'da2-xxxxxxxxxxxxxxxxxxxxxxxxxx'
}
}
});

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:

npx @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:

npx @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:

import { generateClient } from 'aws-amplify/api';
import { createTodo, updateTodo, deleteTodo } from './graphql/mutations';
import { 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!'
}
}
});

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);

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);

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);

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

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

You can then push updated changes with:

amplify 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:

cdk 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:

npx @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:

amplify 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
cdk destroy
cdk 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: