Set up Amplify Data
In this guide, you will learn how to set up Amplify Data. This includes building a real-time API and database using TypeScript to define your data model, and securing your API with authorization rules. We will also explore using AWS Lambda to scale to custom use cases.
Before you begin, you will need:
With Amplify Data, you can build a secure, real-time API backed by a database in minutes. After you define your data model using TypeScript, Amplify will deploy a real-time API for you. This API is powered by AWS AppSync and connected to an Amazon DynamoDB database. You can secure your API with authorization rules and scale to custom use cases with AWS Lambda.
Building your data backend
If you've run npm create amplify@latest
already, you should see an amplify/data/resource.ts
file, which is the central location to configure your data backend. The most important element is the schema
object, which defines your backend data models (a.model()
) and custom queries (a.query()
), mutations (a.mutation()
), and subscriptions (a.subscription()
).
1// backend/data/resource.ts2
3import { a, defineData, type ClientSchema } from '@aws-amplify/backend';4
5const schema = a.schema({6 Todo: a7 .model({8 content: a.string(),9 isDone: a.boolean()10 })11 .authorization([a.allow.public()])12});13
14// Used for code completion / highlighting when making requests from frontend15export type Schema = ClientSchema<typeof schema>;16
17// defines the data resource to be deployed18export const data = defineData({ schema });
Every a.model()
automatically creates the following resources in the cloud:
- a DynamoDB database table to store records
- query and mutation APIs to create, read (list/get), update, and delete records
- real-time APIs to subscribe for create, update, and delete events of records
The a.allow.public()
rule designates that anyone authenticated using an API key can create, read, update, and delete todos.
To deploy these resources to your cloud sandbox, run the following CLI command in your terminal:
1npx amplify sandbox
Connect your application code to the data backend
Once the cloud sandbox is up and running, it will also create an amplifyconfiguration.json
file, which includes the relevant connection information to your data backend, like your API endpoint URL and API key.
To connect your frontend code to your backend, you need to:
- configure the Amplify library with the Amplify client configuration file
- generate a new API client from the Amplify library
- make an API request with end-to-end type-safety
In your app's entry point, typically main.tsx for React apps created using Vite, make the following edits:
1// main.tsx2
3import { Amplify } from 'aws-amplify';4import config from '@/amplifyconfiguration.json';5
6Amplify.configure(config);
Write data to your backend
Let's first add a button to create a new todo item. To make a "create Todo" API request, generate the data client using generateClient()
in your frontend code, and then call .create()
operation for the Todo model. The Data client is a fully typed client that gives you in-IDE code completion. To enable this in-IDE code completion capability, pass in the Schema
type to the generateClient
function.
1// TodoList.tsx2
3"use client"4import type { Schema } from '@/amplify/data/resource'5import { generateClient } from 'aws-amplify/data'6import { client } from '@/utils/data'7
8const client = generateClient<Schema>()9
10export default function TodoList() {11 async function createTodo() => {12 await client.models.Todo.create({13 content: window.prompt("Todo content?"),14 isDone: false15 })16 }17
18 return <div>19 <button onClick={createTodo}>Add new todo</button>20 </div>21}
Run the application in local development mode and check your network tab after creating a todo. You should see a successful request to a /graphql
endpoint.
Read data from your backend
Next, list all your todos and then refetch the todos after a todo has been added:
1// TodoList.tsx2
3"use client"4import type { Schema } from '@/amplify/data/resource'5import { useState, useEffect } from 'react'6import { generateClient } from 'aws-amplify/data'7
8const client = generateClient<Schema>()9
10export default function TodoList() {11 const [todos, setTodos] = useState<Schema["Todo"][]>([])12
13 const fetchTodos = async () => {14 const { data: items, errors } = await client.models.Todo.list()15 setTodos(items)16 }17
18 useEffect(() => { fetchTodos() }, [])19
20 async function createTodo() => {21 await client.models.Todo.create({22 content: window.prompt("Todo content?"),23 isDone: false24 })25
26 fetchTodos()27 }28
29 return (30 <div>31 <button onClick={createTodo}>Add new todo</button>32 <ul>33 {todos.map({ id, content } => <li key={id}>{content}</li>)}34 </ul>35 </div>36 )37}
Subscribe to real-time updates
You can also use observeQuery
to subscribe to a live feed of your backend data. Let's refactor the code to use a real-time observeQuery instead.
1// App.tsx2
3"use client"4import type { Schema } from '@/amplify/data/resource'5import { useState, useEffect } from 'react'6import { generateClient } from 'aws-amplify/data'7
8const client = generateClient<Schema>()9
10export default function TodoList() {11 const [todos, setTodos] = useState<Schema["Todo"][]>([])12
13 useEffect(() => {14 const sub = client.models.Todo15 .observeQuery()16 .subscribe({17 next: ({ items }) => {18 setTodos([...items])19 }20 })21
22 return () => sub.unsubscribe()23 }, [])24
25 async function createTodo() => {26 await client.models.Todo.create({27 content: window.prompt("Todo content?"),28 isDone: false29 })30 // no more manual refetchTodos required!31 // - fetchTodos()32 }33
34 return <div>35 <button onClick={createTodo}>Add new todo</button>36 <ul>37 {todos.map({ id, content } => <li key={id}>{content}</li>)}38 </ul>39 </div>40}
Now try to open your app in two browser windows and see how creating a todo in one window automatically adds the todo in the second window as well.
Conclusion
Success! You've learned how to create your first real-time API and database with Amplify Data.
Next steps
There's so much more to discover with Amplify Data. Learn more about: