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:
- The Amplify CLI is installed and configured
- Have an Amplify project already initialized
First, set up your GraphQL API by running:
1amplify add api
1? Select from one of the below mentioned services:2> GraphQL3? Here is the GraphQL API that we will create. Select a setting to edit or continue4> Continue5? 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 <...>/schema9✔ Do you want to edit the schema now? (Y/n)10> yes11Edit the file in your editor: <...>/schema.graphql12✅ 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 to2# all models in this schema. Learn more about authorization rules here: https://docs.amplify.aws/cli/graphql/auth3input AMPLIFY {4 globalAuthRule: AuthRule = { allow: public }5} # FOR TESTING ONLY!6type Todo @model {7 id: ID!8 name: String!9 description: String10}
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
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();
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:
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
The following schema updates require replacement of the underlying DynamoDB table:
- Removing or renaming a model
- Modifying the primary key of a model
- 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
Rebuild GraphQL API
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
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:
- How to model your database table and their access patterns
- Secure your API with fine-grained authorization rules
- Create relationships between different database model
- Add custom business logic to the GraphQL API
- Run search and result aggregation queries
- Connect to machine learning services
- Best practice and examples