Welcome to the very first part of our AWS Amplify Series! In this series, we’ll be working with AWS Amplify, a powerful development tool that gives available tools for the developers to start, build and scale a cloud-backed application, at lightning speed. Throughout these tutorials, we will build an example frontend application with serverless backend resources, including authentication and storage. While we build our cloud-native application, necessary resources will be generated for us. You can check out our example AWS Amplify project’s GitHub repo for the full source code.
Times are changing, especially on the frontend and hybrid application side, really fast. Since the release of AngularJS, nothing is the same for the frontend development. For the last 5 years, frontend has been thriving with build tools, package managers and new view engines, e.g React and Vue. Developers are able to use even suggested features of Javascript. Everything is cool, except the one thing that is missing, the infrastructure. Most of the frontend developers are using backends developed by other developers, deploy and run their code using methods that are defined by other engineering teams. That limits the playground of the developers and slows-down the development process. This is where AWS Amplify comes in. AWS Amplify enables developers to build and scale their frontend applications in the cloud without backend effort.
AWS Amplify has a lot of great and powerful features which you can check out all of them here. You can add storage, notifications and authentication to any application without hustle. One thing to realize through this series is that all of those features use AWS Services under the hood. Amplify automatically generates many resources through CloudFormation for you. This definitely amplifies the developer experience.
AWS Amplify is a set of tools and services that enables mobile and front-end web developers to build secure, scalable full stack applications, powered by AWS.
aws.amazon.com/amplify/For this tutorial series, we will be building a library application, which will show books, their details, availability etc. We will build a frontend application with serverless backend resources in this case. We will add a GraphQL backend for book details and deploy our application in the cloud. Series will continue with adding authentication including third party logins (Facebook, Google etc.) through Amazon Cognito, role management, S3 for content storage, messaging between book-worms and a mobile app client afterwards.
First things first, let’s start by installing Amplify CLI. You’ll need an AWS account, NodeJS, npm and git, that’s it. Go ahead and type into your terminal:
npm install -g @aws-amplify/cli
After installation, we need to configure Amplify CLI:
amplify configure
You’ll need to pick a region, I’m choosing eu-west-1, you can pick whatever region you want. Name your profile,
and it will open up a link for you to add a programmatically access user to your account. Give your user a
username and give it AdministratorAccess
policy (it is preselected when you follow the link). This ensures that
you can generate resources using your Amplify CLI.
Bootstrap the React project, using create-react-app, and navigate into it:
npx create-react-app library-app-amplified
cd library-app-amplified
Now that we've initialized our application, let's initialize a new backend, and make it amplified!
amplify init
Enter a project name (must be alphanumeric), pick an environment, dev
for development environment, and pick your
IDE, I'm using Visual Studio Code. We're building a React browser app, so pick javascript
from app type choices,
then pick react
. For create-react-app applications, source directory is src
, output directory is build
,
build command is npm run build
, project start command is npm start
. After you’ve picked your profile, you
can see that it is adding a backend for our React application.
Let's go ahead and check our resources in the AWS Console. Cloudformation script has generated a few resources for us. There's a deployment bucket in S3:
A new stack in CloudFormation:
And two new roles in IAM, called authRole
and unauthRole
:
Now that we've amplified our application, let's continue by adding an API. We want our application to use GraphQL, which will store our book data. Let's add API to our application:
amplify add api
Amplify let's you make a lot of choices on this one. Let's pick GraphQL
, API Key
, and for "Choose a schema template"
option, pick Single object with fields
to add a basic schema and edit.
You'll see that it added a folder under your project path /amplify/backend/api/yourapiname/
. Let's go and edit schemas.graphql
and add our Book model.
type Book @model {
id: ID!
name: String!
author: String!,
description: String,
available: Boolean!,
score: Float!
}
Our book model will have a few properties, an id, name, description, author, available field for availability and a score field for rates. Now that we've added our backend, we can do
amplify push
to provision our resources in cloud.
As you can see from the output, Amplify has done a lot of code generations for us. It generated our queries, mutations, subscriptions. Also for the first run, it generated our endpoint in AWS AppSync and DynamoDB tables as a data store. At the very end, it also provided us our API endpoint with the API Key. You can go check out our endpoint in the AWS AppSync Console.
Also you can see that it generated our GraphQL mutations and queries under src/graphql
. Now let's make use of these and list our book information in our application.
It's time to connect your application with your resources. First let's add aws-amplify
library to our project:
npm install --save aws-amplify
When we ran our script amplify init
in the beginning, Amplify added a src/aws-exports.js
file to our project.
It is a generated file so please don't edit it, but you can check its contents and see that it has our GraphQL API
endpoint. We will initialize Amplify with these settings in our code. Let's open our app entry file src/index.js
and add:
import Amplify from "aws-amplify";
import awsExports from "./aws-exports";
Amplify.configure(awsExports);
We've connected our app with Amplify framework. Let's go ahead to your src/App.js
and list our books.
import React, { useEffect, useState } from "react";
import "./App.css";
import { API, graphqlOperation } from "aws-amplify";
import { listBooks } from "./graphql/queries";
function App() {
const [books, setBooks] = useState([]);
const [fetching, setFetching] = useState(false);
async function fetchBooks() {
setFetching(true);
try {
const bookData = await API.graphql(graphqlOperation(listBooks));
const books = bookData.data.listBooks.items;
setBooks(books);
setFetching(false);
} catch (err) {
console.error("error fetching books!");
}
setFetching(false);
}
useEffect(() => {
fetchBooks();
}, []);
return (
<div className="App">
<header className="App-header"><h1>Book Store</h1></header>
<div>
{fetching ? (
<p>Fetching books...</p>
) : (
<>
<h2>Our books:</h2>
{books.length > 0 ? (
<ul>
{books.map((book) => (
<li>
<p>{book.title}</p>
</li>
))}
</ul>
) : (
<p>We don't have any books right now.</p>
)}
</>
)}
</div>
</div>
);
}
export default App;
When you run the application, you'll see that we have no books in our application yet. Let's add a form to add a book and update our data store.
import React, { useEffect, useState } from "react";
import "./App.css";
import { API, graphqlOperation } from "aws-amplify";
import { listBooks } from "./graphql/queries";
import { createBook } from "./graphql/mutations";
function App() {
const [books, setBooks] = useState([]);
const [fetching, setFetching] = useState(false);
async function fetchBooks() {
setFetching(true);
try {
const bookData = await API.graphql(graphqlOperation(listBooks));
const books = bookData.data.listBooks.items;
setBooks(books);
setFetching(false);
} catch (err) {
console.error("error fetching books!");
}
setFetching(false);
}
useEffect(() => {
fetchBooks();
}, []);
const [bookForm, setBookForm] = useState({
name: "",
author: "",
description: "",
available: true,
score: 0
});
const handleChange = (key) => {
return (e) => {
setBookForm({
...bookForm,
[key]: e.target.value
});
}
}
const handleSubmit = (e) => {
e.preventDefault();
API.graphql(graphqlOperation(createBook, { input: bookForm })).then(e => {
setBookForm({
name: "",
author: "",
description: "",
available: true,
score: 0
});
return fetchBooks();
}).catch(err => {
console.error(err);
});
}
return (
<div className="App">
<header className="App-header"><h1>Book Store</h1></header>
<div className="wrapper">
<div>
{fetching ? (
<p>Fetching books...</p>
) : (
<div>
<h2>Our books:</h2>
{books.length > 0 ? (
<ul>
{books.map((book) => (
<li>
<p>{book.name} - {book.author}</p>
</li>
))}
</ul>
) : (
<p>We don't have any books right now <span role="img">😢</span></p>
)}
</div>
)}
</div>
<hr />
<form onSubmit={handleSubmit}>
<h2>Add new Book</h2>
<input placeholder="Book Name" type="text" onChange={handleChange("name")} />
<input placeholder="Author" type="text" onChange={handleChange("author")} />
<input placeholder="Description" type="text" onChange={handleChange("description")} />
<input placeholder="Score" type="number" onChange={handleChange("score")} />
<button type="submit">Add Book</button>
</form>
</div>
</div>
);
}
export default App;
Let's go and add a few books.
Now that we've added our books and we can see them. Our application is ready to be published.
Go ahead to your terminal and add hosting
:
amplify add hosting
Let's pick Hosting with Amplify Console
and Manual Deployment
for now. To publish our app, we need to run:
amplify publish
We have successfully deployed our application! You can check out your deployment at Amplify Console. Now we are serving our frontend application globally with AWS Amplify, fastly through a content delivery network provided by AWS.
Library application to demonstrate power of AWS Amplify. Uses GraphQL API and Hosting.
github.com/sufleio/library-app-amplifiedYou can also use custom domains with your application. Although we will not get into this topic, you can check it out on AWS Amplify Custom Domain documents.
Follow us in the next steps to implement authentication and storage into your application:
The powerful development platform, AWS Amplify allows you to add authentication and roles via groups to limit resource access in your frontend application with ease.
sufle.io/blog/aws-amplify-authentication-part-2AWS Amplify provides a set of built-in components to add storage, file and image management into your frontend application in minutes, fully integrated with Amazon S3.
sufle.io/blog/aws-amplify-storage-part-3An experienced software engineer, Durul is indeed a technology lover and always excited to see and learn what technology offers. With his experience in startups from Entertainment to SaaS, he is keen on sharing his experience with the technology community.
Subscribe to Our Newsletter
Our Service
Specialties
Copyright © 2018-2024 Sufle
We use cookies to offer you a better experience with personalized content.
Cookies are small files that are sent to and stored in your computer by the websites you visit. Next time you visit the site, your browser will read the cookie and relay the information back to the website or element that originally set the cookie.
Cookies allow us to recognize you automatically whenever you visit our site so that we can personalize your experience and provide you with better service.