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:
amplify add api
Accept the default values which are highlighted below:
? Select from one of the below mentioned services: GraphQL? Here is the GraphQL API that we will create. Select a setting to edit or continue Continue? 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
# This "input" configures a global authorization rule to enable public access to# all models in this schema. Learn more about authorization rules here: https://docs.amplify.aws/react/build-a-backend/graphqlapi/customize-authorization-rules/
input AMPLIFY { globalAuthRule: AuthRule = { allow: public }} # FOR TESTING ONLY!type Todo @model { id: ID! name: String! description: String}
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:
amplify push
Choose the following values for each prompt:
✔ Are you sure you want to continue? (Y/n) · yes...? Do you want to generate code for your newly created GraphQL API: Yes? Choose the code generation language target: typescript? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.ts? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Yes? Enter maximum statement depth [increase from default if your schema is deeply nested]: 2? Enter the file name for the generated code: src/API.ts
✔ Are you sure you want to continue? (Y/n) · yes...? Do you want to generate code for your newly created GraphQL API Yes? Choose the code generation language target javascript? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.js? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes? Enter maximum statement depth [increase from default if your schema is deeply nested] 2? 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:
amplify 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:
Current Environment: dev
┌──────────┬───────────────────────┬───────────┬───────────────────┐│ Category │ Resource name │ Operation │ Provider plugin │├──────────┼───────────────────────┼───────────┼───────────────────┤│ Api │ your-api-name │ No Change │ awscloudformation │└──────────┴───────────────────────┴───────────┴───────────────────┘
Review deployed API in AWS console
To view the GraphQL API in the AppSync console at any time, run the following command:
amplify console api
To view your entire app in the Amplify console at any time, run the following command:
amplify 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.
amplify mock api
Note: amplify mock api
requires Java.
# If you have not already deployed your API, you will be walked through the following steps for GraphQL code generation? Choose the code generation language target: javascript (or preferred target)? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Yes? 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:
mutation CreateTodo { createTodo(input: { name: "Test Todo", description: "Todo description" }) { id owner name updatedAt createdAt description }}
Next, update auth to Use: API Key and try querying the list of todos:
query ListTodos { listTodos { items { description createdAt id owner name } }}
Connect frontend to API
First, create a todos
Angular component:
npx ng generate component --standalone todos
In src/app/app.component.ts
update it to import TodosComponent
and add it to the Component imports:
import { Component } from '@angular/core';import { CommonModule } from '@angular/common';import { RouterOutlet } from '@angular/router';import { TodosComponent } from './todos/todos.component';
@Component({ selector: 'app-root', standalone: true, imports: [CommonModule, RouterOutlet, TodosComponent], templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'amplify-app';}
Open src/app/app.component.html
, and replace the default content with the Angular component you created:
<app-todos></app-todos>
In your src/app/todos/todos.component.ts
file, add data to your database with a mutation by using the API.ts
file which was generated when you ran amplify add api
. Additionally, make sure to import the needed form helpers as well as adding ReactiveFormsModule
to your Component imports:
import { Component } from '@angular/core';import { FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';import { generateClient, type Client } from 'aws-amplify/api';import { Todo, ListTodosQuery } from '../../API';import * as mutations from '../../graphql/mutations';
@Component({ standalone: true, imports: [ReactiveFormsModule], selector: 'app-todos', templateUrl: './todos.component.html', styleUrls: ['./todos.component.css']})export class TodosComponent { public createForm: FormGroup; public client: Client;
constructor(private fb: FormBuilder) { this.createForm = this.fb.group({ name: ['', Validators.required], description: ['', Validators.required] });
this.client = generateClient(); }
public async onCreate(todo: Todo) { try { const response = await this.client.graphql({ query: mutations.createTodo, variables: { input: todo } }); console.log('item created!', response); this.createForm.reset(); } catch (e) { console.log('error creating todo...', e); } }}
Next, add a form that will be used for creating todos. Add the following to your src/app/todos/todos.component.html
:
<div class="form-body"> <form autocomplete="off" [formGroup]="createForm" (ngSubmit)="onCreate(createForm.value)" > <div> <label>Name: </label> <input type="text" formControlName="name" autocomplete="off" /> </div> <div> <label>Description: </label> <input type="text" formControlName="description" autocomplete="off" /> </div> <button type="submit">Submit</button> </form></div>
Next, update your TodosComponent
class so that it will list all todos in the database when the app starts. To do so, implement OnInit and add a ListTodos
query in src/app/todos/todos.component.ts
. Store the query results in an array.
import { Component, OnInit } from '@angular/core';import { FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import { generateClient, type Client } from 'aws-amplify/api';import { ListTodosQuery, Todo } from '../../API';import * as mutations from '../../graphql/mutations';import * as queries from '../../graphql/queries';
@Component({ standalone: true, selector: 'app-todos', imports: [ReactiveFormsModule], templateUrl: './todos.component.html', styleUrls: ['./todos.component.css']})export class TodosComponent implements OnInit { public createForm: FormGroup; public client: Client;
/* declare todos variable */ public todos: ListTodosQuery['listTodos'];
constructor(private fb: FormBuilder) { this.createForm = this.fb.group({ name: ['', Validators.required], description: ['', Validators.required] });
this.client = generateClient(); }
async ngOnInit() { /* fetch todos when app loads */ try { const response = await this.client.graphql({ query: queries.listTodos }); this.todos = response.data.listTodos; } catch (e) { console.log('error fetching todos', e); } }
public async onCreate(todo: Todo) { try { const response = await this.client.graphql({ query: mutations.createTodo, variables: { input: todo } }); console.log('item created!', response); this.createForm.reset(); } catch (e) { console.log('error creating todo...', e); } }}
Add the following to your src/app/todos/todos.component.html
to display any of the todos you have added:
<div> @for (todo of todos?.items; track todo?.id) { <div>{{ todo?.name }}</div> <div>{{ todo?.description }}</div> } @empty { <div>There are no items.</div> }</div>
To subscribe to realtime data, declare a subscription class variable and update ngOnInit
in src/app/todos.component.ts
. When the app starts, this code will set up a subscription. The subscription will update the todos
array when new events are received (when a new todo is created):
...
import * as subscriptions from '../../graphql/subscriptions'
export class TodosComponent implements OnInit {
private subscription: any = null;
...
async ngOnInit() {
...
try { const res = await this.client.graphql({ query: queries.listTodos }) console.log(res)
this.todos = res.data.listTodos.items; } catch(e) { console.log(e) };
/* subscribe to new todos being created */ this.subscription = this.client.graphql({ query: subscriptions.onCreateTodo }).subscribe({ next: (event: any) => { const newTodo = event.data.onCreateTodo; if(this.todos) { this.todos.items = [newTodo, ...this.todos.items]; } } }); }}
Finally, unsubscribe from the subscription when the component is destroyed. Import and add OnDestroy
in src/app/todos.component.ts
:
import { Component, OnDestroy, OnInit } from '@angular/core';
...
export class TodosComponent implements OnInit, OnDestroy {
...
ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } this.subscription = null; }}
The final todos.component.ts
file should look like the following:
import { Component, OnInit, OnDestroy } from '@angular/core';import { FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import { generateClient, type Client } from 'aws-amplify/api';import { Todo, ListTodosQuery } from '../../API';import * as mutations from '../../graphql/mutations';import * as queries from '../../graphql/queries';import * as subscriptions from '../../graphql/subscriptions';
@Component({ standalone: true, selector: 'app-todos', imports: [ReactiveFormsModule], templateUrl: './todos.component.html', styleUrls: ['./todos.component.css']})export class TodosComponent implements OnInit, OnDestroy { public todos: ListTodosQuery['listTodos']; public createForm: FormGroup; public client: Client;
private subscription: any = null;
constructor(private fb: FormBuilder) { this.createForm = this.fb.group({ name: ['', Validators.required], description: ['', Validators.required] });
this.client = generateClient(); }
async ngOnInit() { /* fetch todos when app loads */ try { const response = await this.client.graphql({ query: queries.listTodos }); this.todos = response.data.listTodos; } catch (e) { console.log('error fetching todos', e); }
this.subscription = this.client .graphql({ query: subscriptions.onCreateTodo }) .subscribe({ next: (event: any) => { const newTodo: Todo = event.data.onCreateTodo; if (this.todos) { this.todos.items = [newTodo, ...this.todos.items]; } } }); }
ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } this.subscription = null; }
public async onCreate(todo: Todo) { try { const response = await this.client.graphql({ query: mutations.createTodo, variables: { input: todo } }); console.log('item created!', response); this.createForm.reset(); } catch (e) { console.log('error creating todo...', e); } }}
Run locally
Next, run the app and you should see the updated UI with the ability to create and view the list of todos:
npm start
You have successfully deployed your API and connected it to your app!