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

In this section you will create a way to list and create todos from the React application. To do this, you will create a form with a button to create todos as well as a way to fetch and render the list of todos.

Open src/App.tsx and replace it with the following code:

1import { useEffect, useState } from 'react';
2
3import { generateClient } from 'aws-amplify/api';
4
5import { createTodo } from './graphql/mutations';
6import { listTodos } from './graphql/queries';
7import { type CreateTodoInput, type Todo } from './API';
8
9const initialState: CreateTodoInput = { name: '', description: '' };
10const client = generateClient();
11
12const App = () => {
13 const [formState, setFormState] = useState<CreateTodoInput>(initialState);
14 const [todos, setTodos] = useState<Todo[] | CreateTodoInput[]>([]);
15
16 useEffect(() => {
17 fetchTodos();
18 }, []);
19
20 async function fetchTodos() {
21 try {
22 const todoData = await client.graphql({
23 query: listTodos,
24 });
25 const todos = todoData.data.listTodos.items;
26 setTodos(todos);
27 } catch (err) {
28 console.log('error fetching todos');
29 }
30 }
31
32 async function addTodo() {
33 try {
34 if (!formState.name || !formState.description) return;
35 const todo = { ...formState };
36 setTodos([...todos, todo]);
37 setFormState(initialState);
38 await client.graphql({
39 query: createTodo,
40 variables: {
41 input: todo,
42 },
43 });
44 } catch (err) {
45 console.log('error creating todo:', err);
46 }
47 }
48
49 return (
50 <div style={styles.container}>
51 <h2>Amplify Todos</h2>
52 <input
53 onChange={(event) =>
54 setFormState({ ...formState, name: event.target.value })
55 }
56 style={styles.input}
57 value={formState.name}
58 placeholder="Name"
59 />
60 <input
61 onChange={(event) =>
62 setFormState({ ...formState, description: event.target.value })
63 }
64 style={styles.input}
65 value={formState.description as string}
66 placeholder="Description"
67 />
68 <button style={styles.button} onClick={addTodo}>
69 Create Todo
70 </button>
71 {todos.map((todo, index) => (
72 <div key={todo.id ? todo.id : index} style={styles.todo}>
73 <p style={styles.todoName}>{todo.name}</p>
74 <p style={styles.todoDescription}>{todo.description}</p>
75 </div>
76 ))}
77 </div>
78 );
79};
80
81const styles = {
82 container: {
83 width: 400,
84 margin: "0 auto",
85 display: "flex",
86 flexDirection: "column",
87 justifyContent: "center",
88 padding: 20,
89 },
90 todo: { marginBottom: 15 },
91 input: {
92 border: "none",
93 backgroundColor: "#ddd",
94 marginBottom: 10,
95 padding: 8,
96 fontSize: 18,
97 },
98 todoName: { fontSize: 20, fontWeight: "bold" },
99 todoDescription: { marginBottom: 0 },
100 button: {
101 backgroundColor: "black",
102 color: "white",
103 outline: "none",
104 fontSize: 18,
105 padding: "12px 0px",
106 },
107} as const;
108
109export default App;

Open src/App.jsx and replace it with the following code:

1import { useEffect, useState } from 'react';
2
3import { generateClient } from 'aws-amplify/api';
4
5import { createTodo } from './graphql/mutations';
6import { listTodos } from './graphql/queries';
7
8const initialState = { name: '', description: '' };
9const client = generateClient();
10
11const App = () => {
12 const [formState, setFormState] = useState(initialState);
13 const [todos, setTodos] = useState([]);
14
15 useEffect(() => {
16 fetchTodos();
17 }, []);
18
19 function setInput(key, value) {
20 setFormState({ ...formState, [key]: value });
21 }
22
23 async function fetchTodos() {
24 try {
25 const todoData = await client.graphql({
26 query: listTodos
27 });
28 const todos = todoData.data.listTodos.items;
29 setTodos(todos);
30 } catch (err) {
31 console.log('error fetching todos');
32 }
33 }
34
35 async function addTodo() {
36 try {
37 if (!formState.name || !formState.description) return;
38 const todo = { ...formState };
39 setTodos([...todos, todo]);
40 setFormState(initialState);
41 await client.graphql({
42 query: createTodo,
43 variables: {
44 input: todo
45 }
46 });
47 } catch (err) {
48 console.log('error creating todo:', err);
49 }
50 }
51
52 return (
53 <div style={styles.container}>
54 <h2>Amplify Todos</h2>
55 <input
56 onChange={(event) => setInput('name', event.target.value)}
57 style={styles.input}
58 value={formState.name}
59 placeholder="Name"
60 />
61 <input
62 onChange={(event) => setInput('description', event.target.value)}
63 style={styles.input}
64 value={formState.description}
65 placeholder="Description"
66 />
67 <button style={styles.button} onClick={addTodo}>
68 Create Todo
69 </button>
70 {todos.map((todo, index) => (
71 <div key={todo.id ? todo.id : index} style={styles.todo}>
72 <p style={styles.todoName}>{todo.name}</p>
73 <p style={styles.todoDescription}>{todo.description}</p>
74 </div>
75 ))}
76 </div>
77 );
78};
79
80const styles = {
81 container: {
82 width: 400,
83 margin: '0 auto',
84 display: 'flex',
85 flexDirection: 'column',
86 justifyContent: 'center',
87 padding: 20
88 },
89 todo: { marginBottom: 15 },
90 input: {
91 border: 'none',
92 backgroundColor: '#ddd',
93 marginBottom: 10,
94 padding: 8,
95 fontSize: 18
96 },
97 todoName: { fontSize: 20, fontWeight: 'bold' },
98 todoDescription: { marginBottom: 0 },
99 button: {
100 backgroundColor: 'black',
101 color: 'white',
102 outline: 'none',
103 fontSize: 18,
104 padding: '12px 0px'
105 }
106};
107
108export default App;

useEffect - After the component renders, the useEffect hook is called and it invokes the fetchTodos function.

fetchTodos - Uses the Amplify API client created by generateClient() to call the AppSync GraphQL API with the listTodos query. Once the data is returned, the items array is passed in to the setTodos function to update the local state.

addTodo - Uses the Amplify API client created by generateClient() to call the AppSync GraphQL API with the createTodo mutation. A difference between the listTodos query and the createTodo mutation is that createTodo accepts an argument containing the variables needed for the mutation.

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!