Page updated Mar 12, 2024

Preview: AWS Amplify's new code-first DX (Gen 2)

The next generation of Amplify's backend building experience with a TypeScript-first DX.

Get started

Connect API and database to the app

Now that you’ve created and configured your application and initialized a new Amplify project, you can add a feature. The first feature you will add is an API.

The Amplify CLI supports creating and interacting with two types of API categories: REST and GraphQL.

The API you will be creating in this step is a GraphQL API using AWS AppSync (a managed GraphQL service) and the database will be Amazon DynamoDB (a NoSQL database).

Create a GraphQL API and database

Add a GraphQL API to your app and automatically provision a database by running the following command from the root of your application directory:

1amplify add api

Accept the default values which are highlighted below:

1? Select from one of the below mentioned services: GraphQL
2? Here is the GraphQL API that we will create. Select a setting to edit or continue Continue
3? Choose a schema template: Single object with fields (e.g., “Todo” with ID, name, description)

The CLI will prompt you to open this GraphQL schema in your text editor.

amplify/backend/api/your-api-name/schema.graphql

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/
3
4input AMPLIFY {
5 globalAuthRule: AuthRule = { allow: public }
6} # FOR TESTING ONLY!
7type Todo @model {
8 id: ID!
9 name: String!
10 description: String
11}

The schema generated is for a Todo app. You'll notice a @model directive on the Todo type. This directive is part of the Amplify GraphQL API category.

Amplify GraphQL API provides custom GraphQL directives that allow you to define data models, set up authorization rules, configure serverless functions as resolvers, and more.

A GraphQL type decorated with the @model directive will scaffold out the database table for the type (Todo table), the schema for CRUD (create, read, update, delete) and list operations, and the GraphQL resolvers needed to make everything work together.

From the command line, press enter to accept the schema and continue to the next steps.

Deploying the API

To deploy this backend, run the push command:

1amplify push

Choose the following values for each prompt:

1✔ Are you sure you want to continue? (Y/n) · yes
2...
3? Do you want to generate code for your newly created GraphQL API: Yes
4? Choose the code generation language target: typescript
5? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.ts
6? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Yes
7? Enter maximum statement depth [increase from default if your schema is deeply nested]: 2
8? Enter the file name for the generated code: src/API.ts
1✔ Are you sure you want to continue? (Y/n) · yes
2...
3? Do you want to generate code for your newly created GraphQL API Yes
4? Choose the code generation language target javascript
5? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.js
6? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes
7? Enter maximum statement depth [increase from default if your schema is deeply nested] 2
8? Enter the file name for the generated code src/API.js

Now the API is live and you can start interacting with it! The API you have deployed includes operations for creating, reading, updating, deleting, and listing posts.

Review deployment status

Next, run the following command to check Amplify's status:

1amplify status

This will give us the current status of the Amplify project, including the current environment, any categories that have been created, and what state those categories are in. It should look similar to this:

1Current Environment: dev
2
3┌──────────┬───────────────────────┬───────────┬───────────────────┐
4│ Category │ Resource name │ Operation │ Provider plugin │
5├──────────┼───────────────────────┼───────────┼───────────────────┤
6│ Api │ your-api-name │ No Change │ awscloudformation │
7└──────────┴───────────────────────┴───────────┴───────────────────┘
Review deployed API in AWS console

To view the GraphQL API in the AppSync console at any time, run the following command:

1amplify console api

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

1amplify console
Test API with local mocking

To test this out locally, you can run the mock command. Note: Refer to the instructions to setup mocking.

If you'd like to go ahead and connect the front end, you can jump to the next step.

1amplify mock api

Note: amplify mock api requires Java.

1# If you have not already deployed your API, you will be walked through the following steps for GraphQL code generation
2? Choose the code generation language target: javascript (or preferred target)
3? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js
4? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Yes
5? Enter maximum statement depth [increase from default if your schema is deeply nested] 2

This will open the GraphiQL explorer on a local port. From the test environment you can try out different operations locally, like queries and mutations.

In the GraphiQL toolbar, select Use: User Pool and try creating a todo:

1mutation CreateTodo {
2 createTodo(input: { name: "Test Todo", description: "Todo description" }) {
3 id
4 owner
5 name
6 updatedAt
7 createdAt
8 description
9 }
10}

Next, update auth to Use: API Key and try querying the list of todos:

1query ListTodos {
2 listTodos {
3 items {
4 description
5 createdAt
6 id
7 owner
8 name
9 }
10 }
11}

Connect frontend to API

Next, open App.vue.

Writing data with GraphQL mutations

To create a new todo in the database, create a client by using the generateClient() operation, then pass the createTodo mutation into client.graphql() along with the data you'd like to write.

1<script setup>
2 import * as mutations from './graphql/mutations';
3 import { generateClient } from 'aws-amplify/api';
4 import { onMounted, ref } from 'vue';
5
6 const name = ref('');
7 const description = ref('');
8
9 const client = generateClient();
10
11 async function addTodo() {
12 if (!name.value || !description.value) return;
13 const todo = { name: name.value, description: description.value };
14 await client.graphql({
15 query: mutations.createTodo,
16 variables: { input: todo }
17 });
18 name.value = '';
19 description.value = '';
20 }
21</script>
22<template>
23 <div id="app">
24 <h1>Todo App</h1>
25 <input type="text" v-model="name" placeholder="Todo name" />
26 <input type="text" v-model="description" placeholder="Todo description" />
27 <button v-on:click="addTodo">Create Todo</button>
28 </div>
29</template>

Reading data with GraphQL queries

To display the data, update App.vue to list all the items in the database by importing queries and then using the onMounted() Vue lifecycle hook to update the page when a query runs on page load:

1<script setup>
2 import * as mutations from './graphql/mutations';
3 import * as queries from './graphql/queries';
4 import { generateClient } from 'aws-amplify/api';
5 import { onMounted, ref } from 'vue';
6
7 const name = ref('');
8 const description = ref('');
9 const todos = ref([]);
10
11 const client = generateClient();
12
13 async function addTodo() {
14 if (!name.value || !description.value) return;
15 const todo = { name: name.value, description: description.value };
16 await client.graphql({
17 query: mutations.createTodo,
18 variables: { input: todo }
19 });
20 name.value = '';
21 description.value = '';
22 }
23
24 async function fetchTodos() {
25 const fetchedTodos = await client.graphql({
26 query: queries.listTodos
27 });
28
29 todos.value = fetchedTodos.data.listTodos.items;
30 }
31
32 onMounted(() => {
33 fetchTodos();
34 });
35</script>
36<template>
37 <div id="app">
38 <h1>Todo App</h1>
39 <input type="text" v-model="name" placeholder="Todo name" />
40 <input type="text" v-model="description" placeholder="Todo description" />
41 <button v-on:click="addTodo">Create Todo</button>
42
43 <div v-for="item in todos" :key="item.id">
44 <h3>{{ item.name }}</h3>
45 <p>{{ item.description }}</p>
46 </div>
47 </div>
48</template>

Real-time data with GraphQL subscriptions

Now if you wish to subscribe to data, import the onCreateTodo subscription and create a new subscription by passing the onCreateTodo subscription on client.graphql() like so:

1<script setup>
2 import * as mutations from './graphql/mutations';
3 import * as queries from './graphql/queries';
4 import * as subscriptions from './graphql/subscriptions';
5 import { generateClient } from 'aws-amplify/api';
6 import { onMounted, ref } from 'vue';
7
8 const name = ref('');
9 const description = ref('');
10 const todos = ref([]);
11
12 const client = generateClient();
13
14 async function addTodo() {
15 if (!name.value || !description.value) return;
16 const todo = { name: name.value, description: description.value };
17 await client.graphql({
18 query: mutations.createTodo,
19 variables: { input: todo }
20 });
21 name.value = '';
22 description.value = '';
23 }
24
25 async function fetchTodos() {
26 const fetchedTodos = await client.graphql({
27 query: queries.listTodos
28 });
29
30 todos.value = fetchedTodos.data.listTodos.items;
31 }
32
33 function subscribeToNewTodos() {
34 client
35 .graphql({
36 query: subscriptions.onCreateTodo
37 })
38 .subscribe({
39 next: ({ data }) => {
40 todos.value = [...todos.value, data.onCreateTodo];
41 }
42 });
43 }
44
45 onMounted(() => {
46 fetchTodos();
47 subscribeToNewTodos();
48 });
49</script>
50<template>
51 <div id="app">
52 <h1>Todo App</h1>
53 <input type="text" v-model="name" placeholder="Todo name" />
54 <input type="text" v-model="description" placeholder="Todo description" />
55 <button v-on:click="addTodo">Create Todo</button>
56
57 <div v-for="item in todos" :key="item.id">
58 <h3>{{ item.name }}</h3>
59 <p>{{ item.description }}</p>
60 </div>
61 </div>
62</template>

Run locally

Next, run the app and you should see the updated UI with the ability to create and view the list of todos:

1npm run dev

You have successfully deployed your API and connected it to your app!