Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.
Gen1 DocsLegacy

Page updated Mar 26, 2026

Amplify Data をセットアップする

このガイドでは、Amplify Data をセットアップする方法を学びます。これには、TypeScript を使用してデータモデルを定義してリアルタイム API とデータベースを構築し、認可ルールで API をセキュアにすることが含まれます。また、カスタムユースケースにスケーリングするために AWS Lambda を使用することも紹介します。

開始する前に、以下が必要です:

Amplify Data を使うと、数分でデータベースによるセキュアで リアルタイム API を構築できます。TypeScript を使用してデータモデルを定義した後、Amplify はリアルタイム API をデプロイします。この API は AWS AppSync によって提供され、Amazon DynamoDB データベースに接続されています。認可ルールで API をセキュアにでき、AWS Lambda でカスタムユースケースにスケーリングできます。

データバックエンドを構築する

すでに npm create amplify@latest を実行している場合、amplify/data/resource.ts ファイルが表示されます。これは、データバックエンドを構成するための中心的な場所です。最も重要な要素は schema オブジェクトで、バックエンドのデータモデル (a.model()) とカスタムクエリ (a.query())、ミューテーション (a.mutation())、サブスクリプション (a.subscription()) を定義します。

amplify/data/resource.ts
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 frontend
export type Schema = ClientSchema<typeof schema>;
// defines the data resource to be deployed
export const data = defineData({
schema,
authorizationModes: {
defaultAuthorizationMode: 'apiKey',
apiKeyAuthorizationMode: { expiresInDays: 30 }
}
});

すべての a.model() は、クラウドで以下のリソースを自動的に作成します:

  • レコードを保存するための DynamoDB データベーステーブル
  • レコードを作成、読取 (リスト/取得)、更新、削除するためのクエリおよびミューテーション API
  • 各レコードが最初に作成されたとき、または最後に更新されたときを追跡するのに役立つ createdAt および updatedAt フィールド
  • レコードの作成、更新、削除イベントをサブスクライブするためのリアルタイム API

allow.publicApiKey() ルールは、API キーで認証されたすべての人が、todo を作成、読取、更新、削除できることを指定します。

これらのリソースをクラウドサンドボックスにデプロイするには、ターミナルで次の CLI コマンドを実行します:

Terminal
npx ampx sandbox

アプリケーションコードをデータバックエンドに接続する

クラウドサンドボックスが起動して実行されている場合、API エンドポイント URL や API キーなどのデータバックエンドへの接続情報を含む amplify_outputs.json ファイルも作成されます。

フロントエンドコードをバックエンドに接続するには、以下を実行する必要があります:

  1. Amplify ライブラリを Amplify クライアント構成ファイル (amplify_outputs.json) で構成する
  2. Amplify ライブラリから新しい API クライアントを生成する
  3. エンドツーエンドの型安全性を備えた API リクエストを実行する

まず、Amplify クライアントライブラリをプロジェクトにインストールします:

Terminal
npm add aws-amplify

アプリのエントリーポイント (通常、Vite で作成された React アプリの main.tsx) で、次の編集を行います:

src/main.tsx
import { Amplify } from 'aws-amplify';
import outputs from '../amplify_outputs.json';
Amplify.configure(outputs);

バックエンドにデータを書き込む

最初に、新しい todo アイテムを作成するボタンを追加しましょう。"create Todo" API リクエストを実行するには、フロントエンドコードで generateClient() を使用してデータクライアントを生成し、Todo モデルの .create() 操作を呼び出します。Data クライアントは完全に型付きされたクライアントで、IDE 内のコード補完を提供します。IDE 内のこのコード補完機能を有効にするには、generateClient 関数に Schema タイプを渡します。

ローカル開発モードで npm run dev でアプリケーションを実行して、todo を作成した後にネットワークタブを確認します。/graphql エンドポイントへの成功したリクエストが表示されるはずです。

.update(...).delete(...) のコード補完を試して、他のミューテーション操作を感じてみてください。

todo-list.component.ts
import type { Schema } from '../amplify/data/resource';
import { Component } from '@angular/core';
import { generateClient } from 'aws-amplify/data';
const client = generateClient<Schema>();
@Component({
selector: 'app-todo-list',
template: `
<button (click)="createTodo()">Add new todo</button>
`
})
export class TodoListComponent {
async createTodo() {
await client.models.Todo.create({
content: window.prompt("Todo content?"),
isDone: false
});
}
}

ローカル開発モードでアプリケーションを実行して、todo を作成した後にネットワークタブを確認します。/graphql エンドポイントへの成功したリクエストが表示されるはずです。

.update(...).delete(...) のコード補完を試して、他のミューテーション操作を感じてみてください。

バックエンドからデータを読み込む

次に、すべての todo をリストし、todo が追加された後に todo を再度取得します:

todo-list.component.ts
import type { Schema } from '../amplify/data/resource';
import { Component, OnInit } from '@angular/core';
import { generateClient } from 'aws-amplify/data';
const client = generateClient<Schema>();
@Component({
selector: 'app-todo-list',
template: `
<div>
<button (click)="createTodo()">Add new todo</button>
<ul>
<li *ngFor="let todo of todos">{{ todo.content }}</li>
</ul>
</div>
`
})
export class TodoListComponent implements OnInit {
todos: Schema['Todo']['type'][] = [];
async ngOnInit() {
await this.fetchTodos();
}
async fetchTodos() {
const { data: items } = await client.models.Todo.list();
this.todos = items;
}
async createTodo() {
await client.models.Todo.create({
content: window.prompt('Todo content?'),
isDone: false
});
await this.fetchTodos();
}
}

リアルタイム更新をサブスクライブする

observeQuery を使用して、バックエンドデータのライブフィードをサブスクライブすることもできます。コードをリアルタイム observeQuery を使用するようにリファクタリングしましょう。

todo-list.component.ts
import type { Schema } from '../../../amplify/data/resource';
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { generateClient } from 'aws-amplify/data';
import { Subscription } from 'rxjs';
const client = generateClient<Schema>();
@Component({
selector: 'app-todos',
standalone: true,
imports: [CommonModule],
template: `
<main>
<h1>My todos</h1>
<button (click)="createTodo()">+ new</button>
<ul>
<li *ngFor="let todo of todos">
{{ todo.content }}
</li>
</ul>
<div>
🥳 App successfully hosted. Try creating a new todo.
<br />
<a href="https://docs.amplify.aws/gen2/start/quickstart/">
Review next steps of this tutorial.
</a>
</div>
</main>
`,
})
export class TodosComponent implements OnInit {
todos: Schema['Todo']['type'][] = [];
subscription?: Subscription;
ngOnInit(): void {
this.listTodos();
}
ngOnDestroy(): void {
this.subscription?.unsubscribe();
}
listTodos() {
try {
this.subscription = client.models.Todo.observeQuery().subscribe({
next: ({ items, isSynced }) => {
this.todos = items;
},
});
} catch (error) {
console.error('error fetching todos', error);
}
}
createTodo() {
try {
client.models.Todo.create({
content: window.prompt('Todo content'),
});
this.listTodos();
} catch (error) {
console.error('error creating todos', error);
}
}
}

2 つのブラウザウィンドウでアプリを開いて、1 つのウィンドウで todo を作成すると、2 番目のウィンドウで自動的に todo が追加されるかどうかを確認してみてください。

.onCreate, .onUpdate, または .onDelete を使用して、特定のイベントをサブスクライブすることもできます。リアルタイムイベントをサブスクライブする を見て、特定のミューテーションイベントへのサブスクリプションの詳細をご覧ください。

結論

成功しました! Amplify Data で初めてのリアルタイム API とデータベースを作成する方法を学びました。

次のステップ

Amplify Data で発見することがたくさんあります。詳細については、以下をご覧ください: