- Home
- >
- Software Development
- >
- Building Serverless Applications with AWS Amplify – InApps 2022
Building Serverless Applications with AWS Amplify – InApps is an article under the topic Software Development Many of you are most interested in today !! Today, let’s InApps.net learn Building Serverless Applications with AWS Amplify – InApps in today’s post !
Read more about Building Serverless Applications with AWS Amplify – InApps at Wikipedia
You can find content about Building Serverless Applications with AWS Amplify – InApps from the Wikipedia website
Thundra sponsored this post.
Serkan Özal
Serkan is co-founder and CTO of Thundra. He has 10+ years of expertise in software development, is an AWS Certified PRO and has a patent on distributed environments. He mainly works on serverless architectures, distributed systems and monitoring tools.
Before serverless, there were servers to manage. Even today, a typical full-stack application requires you to have frontend, backend and operations knowledge — unless serverless comes into the picture.
When people hear of serverless for the first time, they think of a magical vacuum where there are no servers. This is far from the truth. Serverless does not denote “no servers,” as the name implies. You do still have servers, but you no longer need to worry about them.
Serverless providers like AWS offer numerous services that completely abstract the grunt work of managing servers, while still running at scale. If you want to know how to build a full-stack application in the cloud without sweating the small stuff, this article will help you. We’ll learn how to build a full-stack app and deploy it to the cloud with AWS Amplify.
AWS Amplify
AWS has built great tooling around its cloud services to make developers’ lives easier. One of their very useful tools is AWS Amplify, a JavaScript library that lets you build and deploy serverless applications in the cloud.
A full-stack application is a combination of client-side and server-side code. This may include the UI component, server processing logic, database, push notifications, and more. Without the abstraction that AWS Amplify provides, these components take expertise to wire up to build a scalable application.
In addition to abstraction, AWS Amplify provides pre-built UI components for most of the popular JavaScript frameworks — including React, React Native, Vue and AngularJS.
AWS Amplify Components
You can think of AWS Amplify as a combination of three components: libraries, UI, and CLI ToolChain. These components work together to manage your application development lifecycle efficiently.
The Library Component
The library component allows you to add, integrate, or interact with AWS cloud services. With the library, you can add secure authentication, data store, file storage, serverless APIs, analytics, push notification, AR/VR, and other features to your app.
UI Components
AWS Amplify provides you with pre-built UI components modeled around cloud workflows in your application, such as the authentication higher-order component — which we’ll discuss later in this article.
CLI Toolchain
As your application grows, you might need to add more cloud services. The CLI component of AWS Amplify provides easy-to-use CLI commands to make changes to your AWS-managed backends.
AWS Amplify Features
Before we get our hands dirty with code, it’s essential to know what you can do with AWS Amplify for everyday use cases.
Bootstrap Serverless Application
Amplify CLI allows you to bootstrap client code with fully connected serverless backend infrastructure. The UI components are customizable and optional.
Deploy and Host Applications
For an application to provide value, it must be available to users. A beautiful application sitting in a GitHub repository provides no benefits unless you deploy it. AWS Amplify Console lets you host your static web applications. Once your repository is connected, it automatically deploys new changes in the repository in seconds. The deployment method depends on the build settings you’ve configured for your app.
Building a Full Stack To-Do App with AWS Amplify
A really useful app for managing your day is Google Task. In this tutorial, we’ll build a simpler web app version of Google Task, a to-do app that will let you add tasks, see the tasks you added, and of course, add authentication using AWS Amplify.
Here’s the high-level architecture showing what the end product will look like:
Setting up the Project
To set up a project with AWS Amplify, you’ll need to have an AWS account. Now let’s get started.
Step 1: Install the Amplify CLI.
This library will be used to interact with cloud services (CLI Toolchain).
npm i –g @aws–amplify/cli |
Step 2: Configure AWS Amplify.
This requires you to sign in and then takes you through questions to set up Amplify for your project.
After signing in, you’ll be asked to create an IAM user as the user who has access to your AWS account.
To create an IAM user, answer the questions about AWS Region and IAM user.
Next, you’ll be taken to the IAM Management Console to set up user access. Here’s the user creation flow:
Click “Next” and select “AdministratorAccess” if it’s not selected by default, then continue until you see the “Create user” button.
Click the “Create user” button to create an Amplify user.
The IAM user is created.
Do not close the page. Head back to your terminal, click “Enter,” and provide the accessKeyId
and secretAccessKey
of the newly created user in the terminal.
Step 3: Bootstrap a React application.
For the React project use create-react-app, a well-known library for kick-starting React applications.
To bootstrap the React app, run the command:
npx create–react–app todo–amplify |
With the client code generated, our next step is to initialize the backend.
Initializing the Backend
The to-do app requires backend components like a database to store tasks, AWS Cognito to authenticate users, and GraphQL endpoints. Now we’ll use the AWS Amplify CLI to initialize these components to support our app:
cd todo–amplify amplify init |
You’ll be presented with the following questions (the answers selected for this exercise are shown in brackets):
Enter a name for the project (todo–amplify) Enter a name for the environment (dev) Choose your default editor (VS Code) Choose the type of app that you‘re building (javascript) What JavaScript framework are you using (react) Source directory path (src) Distribution directory path (build) Build command (npm build) Start command (npm start) Do you want to use an AWS profile (Y) |
At this point, you should have a directory called “amplify” created at the root folder. This directory holds all the information about the backend service created. A file called aws-exports.js is also created. This holds the information that will enable you to connect from the client to the back.
In addition to this, the project is now connected to Amplify Console
. You can access the console by running the command amplify console from the terminal.
Setting up the Frontend App
Now that the backend services have been created (and will be updated), the frontend application has to be connected. AWS Amplify provides a variety of UI components for different frameworks. You can install an AWS Amplify UI component for React, our choice of framework for this tutorial, with this command:
npm install aws–amplify @aws–amplify/ui–react —save |
The core library for interacting with AWS services in applications is aws-amplify. The CLI only creates backend services. This library controls how the application connects to the backend and triggers actions.
In addition, @aws-amplify/ui-react
provides React components that connect easily to the backend.
Connecting Amplify in the Frontend App
In src/index.js (the root of the React project), import “aws-exports” and “Amplify” library:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import React from ‘react’; import logo from ‘./logo.svg’; import ‘./App.css’;
import Amplify from “aws-amplify”; import awsExports from “./aws-exports”; Amplify.configure(awsExports);
function App() { return ( <div className=“App”> <header className=“App-header”> <img src={logo} className=“App-logo” alt=“logo” /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className=“App-link” href=“https://reactjs.org” target=“_blank” rel=“noopener noreferrer” > Learn React </a> </header> </div> ); } export default App; |
The aws-exports.js holds the information required to connect and interact with the backend service.
Creating a GraphQL API
An API is the interface through which the frontend and backend communicate. The two main API types today are REST and GraphQL. The latter is the best choice for this project because it is very declarative and lets you fetch only relevant data.
To add an API, use the following command:
Select GraphQL as your API service.
For API name and description, use todo-api and choose a description of what the API manages.
You can answer every other question as you choose. If you’re unsure of what to do, the defaults are fine.
Once you’ve answered all the questions, a GraphQL schema is created in amplify/backend/api/todo-api/schema.graphql:
type Todo @model { id: ID! name: String! description: String } |
If you’re wondering how it knew we were creating a to-do app (in type: Todo), the answer is that it doesn’t. This is the default schema Amplify provides. By default also, this API has already been configured for creating, reading, updating, and deleting (CRUD) to-dos.
For your to-do list, you won’t need a description. Instead, we’ll need a “done” property to denote the to-do’s status. Here’s the updated schema:
type Todo @model { id: ID! name: String! done: Boolean! } |
Now that the API is created, we can deploy it to the cloud.
From your terminal, run the following command:
Connecting the Frontend to API
To do this, we’ll use the methods exposed by GraphQL. In the src directory, there’s an auto-generated GraphQL directory with files that hold different methods.
To view all to-dos and add a to-do, do the following in src/App.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | import React, { useState, useEffect } from “react”; import “./App.css”; import { withAuthenticator, AmplifySignOut } from “@aws-amplify/ui-react”; import { createTodo, updateTodo } from “./graphql/mutations”; import { listTodos } from “./graphql/queries”; import Amplify, { API, graphqlOperation } from “aws-amplify”; import awsExports from “./aws-exports”;
Amplify.configure(awsExports);
function App() { const [allTodos, setAlltodos] = useState(null);
useEffect(() => { (async () => { const todos = await API.graphql(graphqlOperation(listTodos)); setAlltodos(todos.data.listTodos.items); })(); }, []);
const [name, setTodoName] = useState(“”);
const changeTodoName = (e) => { setTodoName(e.target.value); };
const submitAddTodo = async (e) => { e.preventDefault(); if (name === “”) return alert(“Input field cannot be empty”); const todo = { name, done: false }; await API.graphql(graphqlOperation(createTodo, { input: todo })); allTodos === null ? setAlltodos([todo]) : setAlltodos([todo, ...allTodos]); };
const toggleTodo = async (id) => { const todo = allTodos.find(({ id: _id }) => _id === id); let newTodo = { id, name: todo.name }; newTodo.done = todo.done ? false : true; await API.graphql(graphqlOperation(updateTodo, { input: newTodo })); };
return ( <div className=“App”> <div className=“heading”> <h1>Amplify Todo</h1> <div className=“sign-out”> <AmplifySignOut /> </div> </div> <form className=“add-todo-form” onSubmit={submitAddTodo}> <input placeholder=“Add Todo” onChange={changeTodoName} /> <button type=“submit”>+</button> </form> {allTodos === null ? ( <p>Loading Todos...</p> ) : allTodos.length === 0 ? ( <p>No Todo available</p> ) : ( <div className=“todos”> {allTodos.reverse().map(({ id, name, done },i) => ( <div className=“todo-block” key={i}> <input onClick={() => toggleTodo(id)} type=“checkbox” id={id} value={id} key={i} defaultChecked={done} /> <label htmlFor={id}>{name}</label> </div> ))} </div> )} </div> ); }
export default withAuthenticator(App); |
In the useEffect hook, the API to get all to-dos is called, which at first would be empty.
Then the name state is handled and on submit, the createTodo API is called. It receives an input of an object with name and done (with a value of false) properties. Remember the schema demands id (automatically generated), name, and done, so those are what must be submitted when you click the “Submit” button.
When there is a successful response from the createTodo method, instead of refreshing the page, you only update the local state of the todos array.
When a to-do is checked, it’s updated in the backend with a “done” property of “true.” If it’s unchecked, then it’s “false.”
The AmplifySignOut component is exposed from Amplify, and it is used to trigger a sign-out after sign-in. The sign-in setup is shown in the next section (Authentication).
Here’s our application running on localhost:3000 when npm start is run:
Next is authentication.
Authenticating Users
To create the authentication service, run the following:
After answering the questions, run the following:
As you will notice, amplify push
syncs the local updates to the cloud service.
Now, the authentication service is ready. Instead of connecting to the backend manually through the authentication APIs that AWS Amplify provides, you can use the Amplify UI components. For our use case, you would use the withAuthenticator higher-order component.
In src/App.js, add the following:
import { withAuthenticator } from ‘@aws-amplify/ui-react’ ..... export default withAuthenticator(App) |
When you head over to localhost:3000, you’ll get something similar to this:
Amplify will help you manage registration, sign-in, and user authentication for every operation. In this tutorial you can find the full source code used.
Deploying the App
Amplify Console allows you to easily deploy and host applications. To host the app, run the following:
Next, run this:
Your app is now online and you’ll get a public URL on your terminal.
Remember that you can also view your app directly by running the command amplify console
.
If you’d like to delete all the resources or clean up your cloud resources, run the following command:
Amplify: Full-Stack Applications with Less Work
In this post, we’ve seen how to build a full-stack application using AWS Amplify with a minimum amount of work. Without a tool like Amplify, creating full-stack applications would be much harder, and you’d need backend and frontend professionals to do the work. With Amplify, you only need to worry about the end product, and not all that happens inside.
Amazon Web Services is a sponsor of InApps.
Feature image via Pixabay.
At this time, InApps does not allow comments directly on this website. We invite all readers who wish to discuss a story to visit us on Twitter or Facebook. We also welcome your news tips and feedback via email: [email protected].
Source: InApps.net
Let’s create the next big thing together!
Coming together is a beginning. Keeping together is progress. Working together is success.