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()
).
import { a, defineData, type ClientSchema } from '@aws-amplify/backend';
const schema = a.schema({ Todo: a.model({ content: a.string(), isDone: a.boolean() }) .authorization(allow => [allow.publicApiKey()])});
// Used for code completion / highlighting when making requests from frontendexport type Schema = ClientSchema<typeof schema>;
// defines the data resource to be deployedexport const data = defineData({ schema, authorizationModes: { defaultAuthorizationMode: 'apiKey', apiKeyAuthorizationMode: { expiresInDays: 30 } }});
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
createdAt
andupdatedAt
fields that help you keep track of when each record was initially created or when it was last updated- real-time APIs to subscribe for create, update, and delete events of records
The allow.publicApiKey()
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:
npx ampx sandbox
Connect your application code to the data backend
Once the cloud sandbox is up and running, it will also create an amplify_outputs.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 (
amplify_outputs.json
) - Generate a new API client from the Amplify library
- Make an API request with end-to-end type-safety
First, install the Amplify client library to your project:
npm add aws-amplify
In your app's entry point, typically main.ts for Vue apps created using Vite, make the following edits:
import { Amplify } from 'aws-amplify';import outputs from '../amplify_outputs.json';
Amplify.configure(outputs);
Write data to your backend
<script setup lang="ts">import type { Schema } from '../../amplify/data/resource'import { generateClient } from 'aws-amplify/data'
const client = generateClient<Schema>()
async function createTodo() { await client.models.Todo.create({ content: window.prompt("Todo content?"), isDone: false })}</script>
<template> <div> <button @click="createTodo">Add new todo</button> </div></template>
Read data from your backend
Next, list all your todos and then refetch the todos after a todo has been added:
<script setup lang="ts">import { onMounted, ref } from 'vue';import type { Schema } from '../../amplify/data/resource'import { generateClient } from 'aws-amplify/data'
const client = generateClient<Schema>()
// create a reactive reference to the array of todosconst todos = ref<Array<Schema['Todo']['type']>>([]);
function fetchTodos() { const { data: items, errors } = await client.models.Todo.list(); todos.value = items; }
async function createTodo() { await client.models.Todo.create({ content: window.prompt("Todo content?"), isDone: false }) fetchTodos();}
onMounted(() => { fetchTodos();});
</script>
<template> <div> <button @click="createTodo">Add new todo</button> <ul> <li v-for="todo in todos" :key="todo.id"> {{ todo.content }} </li> </ul> </div></template>
Subscribe to real-time updates
<script setup lang="ts">import { onMounted, ref } from 'vue';import type { Schema } from '../../amplify/data/resource'import { generateClient } from 'aws-amplify/data'
const client = generateClient<Schema>()
// create a reactive reference to the array of todosconst todos = ref<Array<Schema['Todo']["type"]>>([]);
function fetchTodos() { client.models.Todo.observeQuery().subscribe({ next: ({ items, isSynced }) => { todos.value = items }, }); }
async function createTodo() { await client.models.Todo.create({ content: window.prompt("Todo content?"), isDone: false }) // no more manual refetchTodos required! // - fetchTodos()}
onMounted(() => { fetchTodos();});
</script>
<template> <div> <button @click="createTodo">Add new todo</button> <ul> <li v-for="todo in todos" :key="todo.id"> {{ todo.content }} </li> </ul> </div></template>
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: