• Stars
    star
    139
  • Rank 261,703 (Top 6 %)
  • Language
    JavaScript
  • Created about 6 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Building Cloud-enabled Mobile Applications with React Native & AWS Amplify

Building Mobile Applications with React Native & AWS Amplify

In this workshop we'll learn how to build cloud-enabled mobile applications with React Native & AWS Amplify.

Amplify React Native Workshop

Topics we'll be covering:

Getting Started - Creating the React Native Application

To get started, we first need to create a new React Native project & change into the new directory using either the React Native CLI (See Building Projects With Native Code in the documentation) or Expo CLI.

We can use the React Native CLI or Expo to create a new app:

If you're using the React Native CLI (you're not using Expo)

Change into the app directory & install the dependencies

$ npx react-native init RNAmplify

$ cd RNAmplify

$ npm install --save aws-amplify aws-amplify-react-native uuid amazon-cognito-identity-js @react-native-community/netinfo

# or

$ yarn add aws-amplify aws-amplify-react-native uuid amazon-cognito-identity-js @react-native-community/netinfo

Next, for iOS you need to install the pods:

$ cd ios

$ pod install --repo-update

$ cd ..

If you are using Expo

$ npx expo init RNAmplify

> Choose a template: blank

$ cd RNAmplify

$ npm install --save aws-amplify aws-amplify-react-native uuid @react-native-community/netinfo

# or

$ yarn add aws-amplify aws-amplify-react-native uuid

Running the app

Next, run the app:

$ npx react-native run-ios

# or if running android

$ npx react-native run-android

# or, if using expo

$ expo start

Installing the CLI & Initializing a new AWS Amplify Project

Installing the CLI

Next, we'll install the AWS Amplify CLI:

$ npm install -g @aws-amplify/cli

Now we need to configure the CLI with our credentials:

$ amplify configure

If you'd like to see a video walkthrough of this configuration process, click here.

Here we'll walk through the amplify configure setup. Once you've signed in to the AWS console, continue:

  • Specify the AWS Region: your preferred region
  • Specify the username of the new IAM user: amplify-workshop-user

In the AWS Console, click Next: Permissions, Next: Tags, Next: Review, & Create User to create the new IAM user. Then, return to the command line & press Enter.

  • Enter the access key of the newly created user:
    accessKeyId: (<YOUR_ACCESS_KEY_ID>)
    secretAccessKey: (<YOUR_SECRET_ACCESS_KEY>)
  • Profile Name: amplify-workshop-user

Initializing A New AWS Amplify Project

Make sure to initialize this Amplify project in the root of your new React Native application

$ amplify init
  • Enter a name for the project: RNAmplify
  • Enter a name for the environment: dev
  • Choose your default editor: Visual Studio Code (or your favorite editor)
  • Please choose the type of app that you're building javascript
  • What javascript framework are you using react-native
  • Source Directory Path: /
  • Distribution Directory Path: /
  • Build Command: npm run-script build
  • Start Command: npm run-script start
  • Select the authentication method you want to use: AWS profile
  • Please choose the profile you want to use: amplify-workshop-user

Now, the AWS Amplify CLI has iniatilized a new project & you will see a couple of new files & folders: amplify & aws-exports.js. These files hold your project configuration.

Configuring the React Native application

The next thing we need to do is to configure our React Native application to be aware of our new AWS Amplify project. We can do this by referencing the auto-generated aws-exports.js file that is now in our root folder.

If you are using the React Native CLI (not using Expo)

To configure the app, open index.js and add the following code below the last import:

// index.js
import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)

Now, our app is ready to start using our AWS services.

If you are using the Expo (not using the React Native CLI)

To configure the app, open App.js and add the following code below the last import:

// App.js
import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)

Now, our app is ready to start using our AWS services.

Adding Authentication

To add authentication, we can use the following command:

$ amplify add auth
  • Do you want to use default authentication and security configuration? Default configuration
  • How do you want users to be able to sign in when using your Cognito User Pool? Username (keep default)
  • Do you want to configure advanced settings? No

Now, we'll run the push command and the cloud resources will be created in our AWS account.

$ amplify push

To view the AWS services any time after their creation, run the following command:

$ amplify console

Using the withAuthenticator component

To add authentication, we'll go into App.js and first import the withAuthenticator HOC (Higher Order Component) from aws-amplify-react:

// App.js
import { withAuthenticator } from 'aws-amplify-react-native'

Next, we'll wrap our default export (the App component) with the withAuthenticator HOC:

export default withAuthenticator(App, {
  includeGreetings: true
})

Now, we can run the app and see that an Authentication flow has been added in front of our App component. This flow gives users the ability to sign up & sign in.

To refresh, you can use one of the following commands:

# iOS Simulator
CMD + d # Opens debug menu
CMD + r # Reloads the app

# Android Emulator
CTRL + m # Opens debug menu
rr # Reloads the app

Accessing User Data

We can access the user's info now that they are signed in by calling Auth.currentAuthenticatedUser().

// App.js
import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  Text,
} from 'react-native';

import { withAuthenticator } from 'aws-amplify-react-native'

import { Auth } from 'aws-amplify' 

class App extends React.Component {
  async componentDidMount() {
    const user = await Auth.currentAuthenticatedUser()
    console.log('user:', user)
  }
  render() {
    return (
      <SafeAreaView style={styles.container}>
        <Text style={styles.title}>Hello World</Text>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  title: {
    fontSize: 28
  }
})

export default withAuthenticator(App, {
  includeGreetings: true
})

Signing out with a custom Sign Out button

We can also sign the user out using the Auth class & calling Auth.signOut(). This function returns a promise that is fulfilled after the user session has been ended & AsyncStorage is updated.

Because withAuthenticator holds all of the state within the actual component, we must have a way to rerender the actual withAuthenticator component by forcing React to rerender the parent component.

To do so, let's make a few updates:

// App.js
import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  Text,
} from 'react-native';

import { withAuthenticator } from 'aws-amplify-react-native'

import { Auth } from 'aws-amplify' 

class App extends React.Component {
  async componentDidMount() {
    const user = await Auth.currentAuthenticatedUser()
    console.log('user:', user)
  }
  signOut = () => {
    Auth.signOut()
      .then(() => this.props.onStateChange('signedOut'))
      .catch(err => console.log('err: ', err))
  }
  render() {
    return (
      <SafeAreaView style={styles.container}>
        <Text style={styles.title}>Hello World</Text>
        <Text onPress={this.signOut}>Sign Out</Text>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  title: {
    fontSize: 28
  }
})

export default withAuthenticator(App);

Custom authentication strategies

To view a final solution for a custom authentication strategy, check out the AWS Amplify React Native Auth Starter here.

This section is an overview and is considered an advanced part of the workshop. If you are not comfortable writing a custom authentication flow, I would read through this section and use it as a reference in the future. If you'd like to jump to the next section, click here.

The withAuthenticator component is a really easy way to get up and running with authentication, but in a real-world application we probably want more control over how our form looks & functions.

Let's look at how we might create our own authentication flow.

To get started, we would probably want to create input fields that would hold user input data in the state. For instance when signing up a new user, we would probably need 3 user inputs to capture the user's username, email, & password.

To do this, we could create some initial state for these values & create an event handler that we could attach to the form inputs:

// initial state
state = {
  username: '', password: '', email: ''
}

// event handler
onChangeText = (key, value) => {
  this.setState({ [key]: value })
}

// example of usage with TextInput
<TextInput
  placeholder='username'
  value={this.state.username}
  style={{ width: 300, height: 50, margin: 5, backgroundColor: "#ddd" }}
  onChangeText={v => this.onChange('username', v)}
/>

We'd also need to have a method that signed up & signed in users. We can us the Auth class to do thi. The Auth class has over 30 methods including things like signUp, signIn, confirmSignUp, confirmSignIn, & forgotPassword. Thes functions return a promise so they need to be handled asynchronously.

// import the Auth component
import { Auth } from 'aws-amplify'

// Class method to sign up a user
signUp = async() => {
  const { username, password, email } = this.state
  try {
    await Auth.signUp({ username, password, attributes: { email }})
  } catch (err) {
    console.log('error signing up user...', err)
  }
}

Adding a GraphQL API with AWS AppSync

To add a GraphQL API, we can use the following command:

$ amplify add api

Answer the following questions

  • Please select from one of the above mentioned services GraphQL
  • Provide API name: RestaurantAPI
  • Choose the default authorization type for the API API key
  • Enter a description for the API key public
  • After how many days from now the API key should expire 365
  • Do you want to configure advanced settings for the GraphQL API No
  • Do you have an annotated GraphQL schema? N
  • Choose a schema template: Single object with fields (e.g. “Todo” with ID, name, description)
  • Do you want to edit the schema now? (Y/n) Y

When prompted, update the schema to the following:

type Restaurant @model {
  id: ID!
  clientId: String
  name: String!
  description: String!
  city: String!
}

Next, deploy the API:

amplify push

? Are you sure you want to continue? 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: ./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)

Optional - To mock and test the API locally, you can run the mock command:

$ amplify mock api

This should start an AppSync Mock endpoint:

AppSync Mock endpoint is running at http://10.219.99.136:20002

Open the endpoint in the browser to use the GraphiQL Editor.

From here, we can now test the API.

Adding mutations from within the GraphiQL Editor.

In the GraphiQL editor, execute the following mutation to create a new restaurant in the API:

mutation createRestaurant {
  createRestaurant(input: {
    name: "Nobu"
    description: "Great Sushi"
    city: "New York"
  }) {
    id name description city
  }
}

Now, let's query for the restaurant:

query listRestaurants {
  listRestaurants {
    items {
      id
      name
      description
      city
    }
  }
}

We can even add search / filter capabilities when querying:

query searchRestaurants {
  listRestaurants(filter: {
    city: {
      contains: "New York"
    }
  }) {
    items {
      id
      name
      description
      city
    }
  }
}

Or, get an individual restaurant by ID:

query getRestaurant {
  getRestaurant(id: "RESTAURANT_ID") {
    name
    description
    city
  }
}

Interacting with the GraphQL API from our client application - Querying for data

Now that the GraphQL API is created we can begin interacting with it!

The first thing we'll do is perform a query to fetch data from our API.

To do so, we need to define the query, execute the query, store the data in our state, then list the items in our UI.

import React from 'react';
import {
  SafeAreaView,
  View,
  StyleSheet,
  Text,
} from 'react-native';

// imports from Amplify library
import { withAuthenticator } from 'aws-amplify-react-native'
import { API, graphqlOperation } from 'aws-amplify'

// import the GraphQL query
import { listRestaurants } from './graphql/queries'

class App extends React.Component {
  // define some state to hold the data returned from the API
  state = {
    restaurants: []
  }
  // execute the query in componentDidMount
  async componentDidMount() {
    try {
      const restaurantData = await API.graphql(graphqlOperation(listRestaurants))
      console.log('restaurantData:', restaurantData)
      this.setState({
        restaurants: restaurantData.data.listRestaurants.items
      })
    } catch (err) {
      console.log('error fetching restaurants...', err)
    }
  }
  render() {
    return (
      <SafeAreaView style={styles.container}>
        {
          this.state.restaurants.map((restaurant, index) => (
            <View key={index} style={styles.item}>
              <Text style={styles.name}>{restaurant.name}</Text>
              <Text style={styles.description}>{restaurant.description}</Text>
              <Text style={styles.city}>{restaurant.city}</Text>
            </View>
          ))
        }
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  item: { padding: 10 },
  name: { fontSize: 20 },
  description: { fontWeight: '600', marginTop: 4, color: 'rgba(0, 0, 0, .5)' },
  city: { marginTop: 4 }
})

export default withAuthenticator(App, { includeGreetings: true });

Performing mutations

Now, let's look at how we can create mutations. The mutation we will be working with is createRestaurant.

// App.js
import React from 'react';
import {
  SafeAreaView,
  View,
  StyleSheet,
  Text,
  TextInput,
  Button
} from 'react-native';

// imports from Amplify library
import { withAuthenticator } from 'aws-amplify-react-native'
import { API, graphqlOperation } from 'aws-amplify'

// import the GraphQL query
import { listRestaurants } from './graphql/queries'
// import the GraphQL mutation
import { createRestaurant } from './graphql/mutations'

// create client ID
import { v4 as uuid } from 'uuid'
const CLIENTID = uuid()

class App extends React.Component {
  // add additional state to hold form state as well as restaurant data returned from the API
  state = {
    name: '', description: '', city: '', restaurants: []
  }
  // execute the query in componentDidMount
  async componentDidMount() {
    try {
      const restaurantData = await API.graphql(graphqlOperation(listRestaurants))
      console.log('restaurantData:', restaurantData)
      this.setState({
        restaurants: restaurantData.data.listRestaurants.items
      })
    } catch (err) {
      console.log('error fetching restaurants...', err)
    }
  }
  // this method calls the API and creates the mutation
  createRestaurant = async() => {
    const { name, description, city  } = this.state
    // store the restaurant data in a variable
    const restaurant = {
      name, description, city, clientId: CLIENTID
    }
    // perform an optimistic response to update the UI immediately
    const restaurants = [...this.state.restaurants, restaurant]
    this.setState({
      restaurants,
      name: '', description: '', city: ''
      })
    try {
      // make the API call
      await API.graphql(graphqlOperation(createRestaurant, {
        input: restaurant
      }))
      console.log('item created!')
    } catch (err) {
      console.log('error creating restaurant...', err)
    }
  }
  // change form state then user types into input
  onChange = (key, value) => {
    this.setState({ [key]: value })
  }
  render() {
    return (
      <SafeAreaView style={styles.container}>
        <TextInput
          style={{ height: 50, margin: 5, backgroundColor: "#ddd" }}
          onChangeText={v => this.onChange('name', v)}
          value={this.state.name} placeholder='name'
        />
        <TextInput
          style={{ height: 50, margin: 5, backgroundColor: "#ddd" }}
          onChangeText={v => this.onChange('description', v)}
          value={this.state.description} placeholder='description'
        />
        <TextInput
          style={{ height: 50, margin: 5, backgroundColor: "#ddd" }}
          onChangeText={v => this.onChange('city', v)}
          value={this.state.city} placeholder='city'
        />
        <Button onPress={this.createRestaurant} title='Create Restaurant' />
        {
          this.state.restaurants.map((restaurant, index) => (
            <View key={index} style={styles.item}>
              <Text style={styles.name}>{restaurant.name}</Text>
              <Text style={styles.description}>{restaurant.description}</Text>
              <Text style={styles.city}>{restaurant.city}</Text>
            </View>
          ))
        }
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  item: { padding: 10 },
  name: { fontSize: 20 },
  description: { fontWeight: '600', marginTop: 4, color: 'rgba(0, 0, 0, .5)' },
  city: { marginTop: 4 }
})

export default withAuthenticator(App, { includeGreetings: true });

Challenge

Recreate this functionality in Hooks

For direction, check out the tutorial here

For the solution to this challenge, view the hooks file.

Adding a Serverless Function

Adding a basic Lambda Function

To add a serverless function, we can run the following command:

$ amplify add function

? Select which capability you want to add: Lambda function
? Provide an AWS Lambda function nam: basiclambda
? Choose the runtime that you want to use: NodeJS
? Choose the function template that you want to use: Hello World
? Do you want to configure advanced settings? N
? Do you want to edit the local lambda function now? Y

This should open the function package located at amplify/backend/function/basiclambda/src/index.js.

Edit the function to look like this, & then save the file.

exports.handler = async (event, contex) => {
  console.log('event: ', event)
  const body = {
    message: "Hello world!"
  }
  const response = {
    statusCode: 200,
    body
  }
  return response
}

Next, we can test this out by running:

$ amplify mock function basiclambda

? Provide the path to the event JSON object: src/event.json

You'll notice the following output from your terminal:

Ensuring latest function changes are built...
Starting execution...
event:  { key1: 'value1', key2: 'value2', key3: 'value3' }
Result:
{
  "statusCode": 200,
  "body": {
    "message": "Hello world!"
  }
}
Finished execution.

Where is the event data coming from? It is coming from the values located in event.json in the function folder (amplify/backend/function/basiclambda/src/event.json). If you update the values here, you can simulate data coming arguments the event.

Feel free to test out the function by updating event.json with data of your own.

Adding a function running an express server and invoking it from an API call (http)

Next, we'll build a function that will be running an Express server inside of it.

This new function will fetch data from a cryptocurrency API & return the values in the response.

To get started, we'll create a new function:

$ amplify add function

? Select which capability you want to add: Lambda function
? Provide an AWS Lambda function name: cryptofunction
? Choose the runtime that you want to use: NodeJS
? Choose the function template that you want to use: Serverless ExpressJS
? Do you want to configure advanced settings? No
? Do you want to edit the local lambda function now? Y

This should open the function package located at amplify/backend/function/cryptofunction/src/index.js. You'll notice in this file, that the event is being proxied into an express server:

exports.handler = (event, context) => {
  console.log(`EVENT: ${JSON.stringify(event)}`);
  awsServerlessExpress.proxy(server, event, context);
};

Instead of updating the handler function itself, we'll instead update amplify/backend/function/cryptofunction/src/app.js which has the actual server code we would like to be working with.

Here, in amplify/backend/function/cryptofunction/src/app.js, we'll add the following code & save the file:

// amplify/backend/function/cryptofunction/src/app.js

// you should see this code already there 👇:
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
});
// below the above code, add the following code 👇 (be sure not to delete any other code from this file)
const axios = require('axios')

app.get('/coins', function(req, res) {
  let apiUrl = `https://api.coinlore.com/api/tickers?start=0&limit=10`
  
  if (req && req.query) {
    // here we are checking to see if there are any query parameters, and if so appending them to the request
    const { start = 0, limit = 10 } = req.query
    apiUrl = `https://api.coinlore.com/api/tickers/?start=${start}&limit=${limit}`
  }

  axios.get(apiUrl)
    .then(response => {
      res.json({
        coins: response.data.data
      })
    })
    .catch(err => res.json({ error: err }))
})

In the above function we've used the axios library to call another API. In order to use axios, we need be sure that it will be installed by updating the package.json for the new function:

$ cd amplify/backend/function/cryptofunction/src

$ npm install axios

$ cd ../../../../../

Next, change back into the root directory.

Adding a REST API

Now that we've created the cryptocurrency Lambda function let's add an API endpoint so we can invoke it via http.

To add the REST API, we can use the following command:

$ amplify add api

? Please select from one of the above mentioned services: REST
? Provide a friendly name for your resource that will be used to label this category in the project: cryptoapi   
? Provide a path (e.g., /items): /coins   
? Choose lambda source: Use a Lambda function already added in the current Amplify project   
? Choose the Lambda function to invoke by this path: cryptofunction   
? Restrict API access: Y
? Who should have access? Authenticated users only
? What kind of access do you want for Authenticated users: read/create/update/delete
? Do you want to add another path? (y/N) N  

Now the resources have been created & configured & we can push them to our account:

$ amplify push

? Are you sure you want to continue? Y

Interacting with the new API

Now that the API is created we can start sending requests to it & interacting with it.

Let's request some data from the API:

// App.js
import React from 'react'
import { View, Text, StyleSheet } from 'react-native'
import { API } from 'aws-amplify'
import { withAuthenticator } from 'aws-amplify-react-native'

class App extends React.Component {
  state = {
    coins: []
  }
  async componentDidMount() {
    try {
      // to get all coins, do not send in a query parameter
      // const data = await API.get('cryptoapi', '/coins')
      const data = await API.get('cryptoapi', '/coins?limit=5&start=100')
      console.log('data from Lambda REST API: ', data)
      this.setState({ coins: data.coins })
    } catch (err) {
      console.log('error fetching data..', err)
    }
  }
  render() {
    return (
      <View>
        {
          this.state.coins.map((c, i) => (
            <View key={i} style={styles.row}>
              <Text style={styles.name}>{c.name}</Text>
              <Text>{c.price_usd}</Text>
            </View>
          ))
        }
      </View>
    )
  }
}

const styles = StyleSheet.create({
  row: { padding: 10 },
  name: { fontSize: 20, marginBottom: 4 },
})

export default withAuthenticator(App, { includeGreetings: true })

Adding Analytics

To add analytics, we can use the following command:

$ amplify add analytics

Next, we'll be prompted for the following:

  • Provide your pinpoint resource name: amplifyanalytics
  • Apps need authorization to send analytics events. Do you want to allow guest/unauthenticated users to send analytics events (recommended when getting started)? Y

To deploy, run the push command:

$ amplify push

Recording events

Now that the service has been created we can now begin recording events.

To record analytics events, we need to import the Analytics class from Amplify & then call Analytics.record:

import { Analytics } from 'aws-amplify'

state = {username: ''}

async componentDidMount() {
  try {
    const user = await Auth.currentAuthenticatedUser()
    this.setState({ username: user.username })
  } catch (err) {
    console.log('error getting user: ', err)
  }
}

recordEvent = () => {
  Analytics.record({
    name: 'My test event',
    attributes: {
      username: this.state.username
    }
  })
}

<Button onPress={this.recordEvent} title='Record Event' />

To view the analytics in the console, run the console command:

$ amplify console

In the console, click on Analytics, then click on View in Pinpoint. In the Pinpoint console, click on events and then enable filters.

Working with Storage

To add storage, we can use the following command:

amplify add storage

Answer the following questions

  • Please select from one of the below mentioned services Content (Images, audio, video, etc.)
  • Please provide a friendly name for your resource that will be used to label this category in the project: rnworkshopstorage
  • Please provide bucket name: YOUR_UNIQUE_BUCKET_NAME
  • Who should have access: Auth users only
  • What kind of access do you want for Authenticated users?
❯◉ create/update
 ◉ read
 ◉ delete
amplify push

Now, storage is configured & ready to use.

What we've done above is created configured an Amazon S3 bucket that we can now start using for storing items.

For example, if we wanted to test it out we could store some text in a file like this:

import { Storage } from 'aws-amplify'

// create function to work with Storage
addToStorage = () => {
  Storage.put('textfiles/mytext.txt', `Hello World`)
    .then (result => {
      console.log('result: ', result)
    })
    .catch(err => console.log('error: ', err));
}

// add click handler
<Button onPress={this.addToStorage} title='Add to Storage' />

This would create a folder called textfiles in our S3 bucket & store a file called mytext.txt there with the code we specified in the second argument of Storage.put.

If we want to read everything from this folder, we can use Storage.list:

readFromStorage = () => {
  Storage.list('textfiles/')
    .then(data => console.log('data from S3: ', data))
    .catch(err => console.log('error fetching from S3', err))
}

If we only want to read the single file, we can use Storage.get:

readFromStorage = () => {
  Storage.get('textfiles/mytext.txt')
    .then(data => {
      console.log('data from S3: ', data)
      fetch(data)
        .then(r => r.text())
        .then(text => {
          console.log('text: ', text)
        })
        .catch(e => console.log('error fetching text: ', e))
    })
    .catch(err => console.log('error fetching from S3', err))
}

If we wanted to pull down everything, we can use Storage.list:

readFromStorage = () => {
  Storage.list('')
    .then(data => console.log('data from S3: ', data))
    .catch(err => console.log('error fetching from S3', err))
}

Multiple Serverless Environments

Now that we have our API up & running, what if we wanted to update our API but wanted to test it out without it affecting our existing version?

To do so, we can create a clone of our existing environment, test it out, & then deploy & test the new resources.

Once we are happy with the new feature, we can then merge it back into our main environment. Let's see how to do this!

Creating a new environment

To create a new environment, we can run the env command:

$ amplify env add

> Do you want to use an existing environment? No
> Enter a name for the environment: apiupdate
> Do you want to use an AWS profile? Yes
> Please choose the profile you want to use: appsync-workshop-profile

Now, the new environment has been initialize, & we can deploy the new environment using the push command:

$ amplify push

Now that the new environment has been created we can get a list of all available environments using the CLI:

$ amplify env list

Let's update the GraphQL schema to add a new field. In amplify/backend/api/RestaurantAPI/schema.graphql update the schema to the following:

type Restaurant @model {
  id: ID!
  clientId: String
  name: String!
  type: String
  description: String!
  city: String!
}

type ModelRestaurantConnection {
	items: [Restaurant]
	nextToken: String
}

type Query {
  listAllRestaurants(limit: Int, nextToken: String): ModelRestaurantConnection
}

In the schema we added a new field to the Restaurant definition to define the type of restaurant:

type: String

Now, we can run amplify push again to update the API:

$ amplify push

To test this out, we can go into the AppSync Console & log into the API.

You should now see a new API called RestaurantAPI-apiupdate. Click on this API to view the API dashboard.

If you click on Schema you should notice that it has been created with the new type field. Let's try it out.

To test it out we need to create a new user because we are using a brand new authentication service. To do this, open the app & sign up.

In the API dashboard, click on Queries.

Next, click on the Login with User Pools link.

Copy the aws_user_pools_web_client_id value from your aws-exports file & paste it into the ClientId field.

Next, login using your username & password.

Now, create a new mutation & then query for it:

mutation createRestaurant {
  createRestaurant(input: {
    name: "Nobu"
    description: "Great Sushi"
    city: "New York"
    type: "sushi"
  }) {
    id name description city type
  }
}

query listRestaurants {
  listAllRestaurants {
    items {
      name
      description
      city
      type
    }
  }
}

Merging the new environment changes into the main environment.

Now that we've created a new environment & tested it out, let's check out the main environment.

$ amplify env checkout local

Next, run the status command:

$ amplify status

You should now see an Update operation:

Current Environment: local

| Category | Resource name   | Operation | Provider plugin   |
| -------- | --------------- | --------- | ----------------- |
| Api      | RestaurantAPI   | Update    | awscloudformation |
| Auth     | cognito75a8ccb4 | No Change | awscloudformation |

To deploy the changes, run the push command:

$ amplify push

Now, the changes have been deployed & we can delete the apiupdate environment:

$ amplify env remove apiupdate

Do you also want to remove all the resources of the environment from the cloud? Y

Now, we should be able to run the list command & see only our main environment:

$ amplify env list

Removing Services

If at any time, or at the end of this workshop, you would like to delete a service from your project & your account, you can do this by running the amplify remove command:

$ amplify remove auth

$ amplify push

If you are unsure of what services you have enabled at any time, you can run the amplify status command:

$ amplify status

amplify status will give you the list of resources that are currently enabled in your app.

Deleting the project

To delete the entire project, run the delete command:

$ amplify delete

More Repositories

1

awesome-aws-amplify

Curated list of AWS Amplify Resources
1,785
star
2

polygon-ethereum-nextjs-marketplace

A full stack digital marketplace running on Ethereum with Polygon & Next.js
JavaScript
1,303
star
3

full-stack-ethereum

Building full stack apps with Solidity, Ethers.js, Hardhat, and The Graph
TypeScript
802
star
4

react-native-ai

Full stack framework for building cross-platform mobile AI apps
TypeScript
794
star
5

semantic-search-nextjs-pinecone-langchain-chatgpt

Embeds text files into vectors, stores them on Pinecone, and enables semantic search using GPT3 and Langchain in a Next.js UI
TypeScript
739
star
6

awesome-aws-appsync

Curated list of AWS AppSync Resources
625
star
7

gpt-travel-advisor

reference architecture for building a travel application with GPT3
TypeScript
543
star
8

foundry-cheatsheet

522
star
9

complete-guide-to-full-stack-solana-development

Code examples for the blog post titled The Complete Guide to Full Stack Solana Development with React, Anchor, Rust, and Phantom
JavaScript
474
star
10

dynamodb-documentclient-cheat-sheet

DynamoDB JavaScript DocumentClient cheat sheet
443
star
11

full-stack-web3

A full stack web3 on-chain blog and CMS
JavaScript
420
star
12

next.js-amplify-workshop

AWS Amplify Next.js workshop
JavaScript
360
star
13

gatsby-auth-starter-aws-amplify

Starter Project with Authentication with Gatsby & AWS Amplify
JavaScript
320
star
14

gpt-fine-tuning-with-nodejs

GPT Fine-Tuning using Node.js - an easy to use starter project
JavaScript
250
star
15

full-stack-serverless-code

Code examples for my book Full Stack Serverless with O'Reilly Publications
JavaScript
244
star
16

openai-functions-god-app

TypeScript
240
star
17

heard

React Native Enterprise Social Messaging App
JavaScript
236
star
18

aws-appsync-react-workshop

Building real-time offline-ready Applications with React, GraphQL & AWS AppSync
JavaScript
228
star
19

nextjs-chatgpt-plugin-starter

ChatGPT plugin starter project using Next.js
TypeScript
209
star
20

micro-frontend-example

Building Micro Frontends with React, Vue, and Single-spa
JavaScript
207
star
21

amplify-photo-sharing-workshop

Building full-stack cloud apps with AWS Amplify and React
JavaScript
197
star
22

chicken-tikka-masala-recipe

Nader's chicken tikka masala recipe
PHP
193
star
23

decentralized-identity-example

An authentication system built with Ceramic & self.id
JavaScript
190
star
24

aws-amplify-workshop-react

Building Serverless React Applications with AWS Amplify
172
star
25

building-a-subgraph-workshop

In this workshop you'll learn how to build an NFT Subgraph using any smart contract or smart contracts.
TypeScript
165
star
26

graphql-recipes

A list of GraphQL recipes that, when used with the Amplify CLI, will deploy an entire AWS AppSync GraphQL backend.
158
star
27

next.js-cdk-amplify-workshop

Full stack serverless workshop with Next.js, CDK, and AWS Amplify
JavaScript
157
star
28

supabase-next.js

Full stack app built with Supabase and Next.js
JavaScript
152
star
29

titter

Decentralized Twitter prototype built with Polygon, GraphQL, Next.js, Ceramic, Arweave, and Bundlr
JavaScript
152
star
30

supabase-nextjs-auth

Example project implementing authentication, authorization, and routing with Next.js and Supabase
JavaScript
151
star
31

react-native-in-action

React Native in Action, written for Manning Publications
146
star
32

prompt-engineering-for-javascript-developers

Notes summarized from ChatGPT Prompt Engineering for Developers by DeepLearning.ai
145
star
33

write-with-me

Real-time Collaborative Markdown Editor
JavaScript
144
star
34

foundry-workshop

Building and testing smart contracts with Foundry
Solidity
144
star
35

lens-protocol-frontend

Example of a basic front end built on Lens Protocol
JavaScript
136
star
36

cdk-graphql-backend

A real-time GraphQL API deployed with CDK using AWS AppSync, AWS Lambda, and DynamoDB
TypeScript
131
star
37

create-new-cli

Create your own CLI using a series of simple commands.
JavaScript
128
star
38

perma

Perma is a web3 prototype of permanent video storage and viewing using Next.js, Arweave, and Bundlr.
JavaScript
120
star
39

appsync-graphql-real-time-canvas

Collaborative real-time canvas built with GraphQL, AWS AppSync, & React Canvas Draw
JavaScript
119
star
40

full-stack-ethereum-marketplace-workshop

Build a Full Stack Marketplace on Ethereum with React, Solidity, Hardhat, and Ethers.js
JavaScript
118
star
41

hype-beats

Real-time Collaborative Beatbox with React & GraphQL
JavaScript
111
star
42

amplify-auth-demo

Demo of OAuth + Username / Password authentication in AWS Amplify
JavaScript
111
star
43

next.js-authentication-aws

This project deploys a Next.js project to AWS with comprehensive authentication enabled
JavaScript
104
star
44

this-or-that

This or that - Real-time atomic voting app built with AWS Amplify
CSS
98
star
45

react-native-deep-linking

Deep Linking set up in a React Native App
Objective-C
96
star
46

beginning-webpack

This repository goes along with the medium post titled "Beginner's guide to Webpack"
JavaScript
95
star
47

react-native-bootcamp

React Native Bootcamp Materials for TylerMcginnis.com
94
star
48

react-native-mobx-list-app

React Native + Mobx List Application
JavaScript
91
star
49

appsync-auth-and-unauth

How to allow both authenticated & unauthenticated access to an API
JavaScript
91
star
50

aws-amplify-workshop-web

Building web applications with React & AWS Amplify
JavaScript
90
star
51

full-stack-ethereum-workshop

Building full stack dapps on the EVM with Hardhat, React, and Ethers.js
HTML
89
star
52

sign-in-with-ethereum-authentication-flow

Example implementation of how to implement Sign In with Ethereum
JavaScript
85
star
53

react-notes

React notes tutorial
JavaScript
84
star
54

vue-graphql-appsync

Vue example using GraphQL with AWS AppSync
JavaScript
81
star
55

lens-pwa

Lens PWA
TypeScript
80
star
56

amplify-datastore-example

Example of basic app using Amplify DataStore
JavaScript
78
star
57

custom-nft-subgraph-workshop

78
star
58

lens-shadcn

Example application combining Lens Protocol, WalletConnect, Next.js, and ShadCN
TypeScript
78
star
59

amplify-with-cdk

An example project showing how to mix CDK with AWS Amplify
TypeScript
77
star
60

react-aws-live-streaming

This project shows how to implement a live-streaming platform using AWS and React
JavaScript
73
star
61

react-native-navigation-v2

Up and running with React Native Navigation - V2 - by Wix
JavaScript
73
star
62

bored-ape-yacht-club-api-and-subgraph

Graph Protocol Subgraph / API for querying Bored Ape Yacht Club NFT data with full text search
TypeScript
70
star
63

react-appsync-graphql-recipe-app

Example application using React + AWS AppSync + GraphQL
JavaScript
70
star
64

react-amplify-appsync-files-s3

An example project showing how to upload and download public and private images in GraphQL using AppSync and S3
JavaScript
70
star
65

react-strict-dom-example

JavaScript
69
star
66

full-stack-react-native-appsync-workshop

Building Full Stack GraphQL Applications with React Native & AWS AppSync
JavaScript
67
star
67

speakerchat

SpeakerChat - Real-time Event Q&A Platform with Markdown Support
JavaScript
66
star
68

react-p2p-messaging

A real-time peer-to-peer messaging app built with React & Gun.js
JavaScript
65
star
69

graphql-suspense

Lightweight component that allows you to interact with a GraphQL API using React Suspense
JavaScript
65
star
70

nuxt-supabase-full-multi-user-blog

Build a mult-user blogging app with Supabase and Nuxt.js
Vue
65
star
71

archive-forever

HTML
63
star
72

next.js-tailwind-authentication

A Next.js authentication starter built with Tailwind and AWS Amplify
JavaScript
63
star
73

near-subgraph-workshop

Building a NEAR NFT API with The Graph
60
star
74

react-authentication-in-depth

Example of User Authentication using React with React Router and AWS Amplify
JavaScript
60
star
75

graphql-api-cdk-serverless-postgres

TypeScript
59
star
76

curious-cases-of-graphql

Code and examples from my talk - Curious Cases of GraphQL
57
star
77

gasless-transactions-example

Example of Gasless Transactions with Biconomy
JavaScript
57
star
78

react-chatbots

Building Chatbots with React, Amazon Lex, AWS Lambda, & AWS Amplify
JavaScript
57
star
79

xmtp-chat-app-nextjs

Real-time encrypted chat, built with XMTP and Next.js
TypeScript
57
star
80

react-native-lens-example

Example app built with React Native Lens UI Kit
JavaScript
55
star
81

lens-protocol-workshop

Introduction to web3 social media with Next.js and Lens Protocol
TypeScript
54
star
82

zora-nextjs-app

Example Full Stack App built with Next.js, Zora, Tailwind, and The Graph
TypeScript
54
star
83

draw-together

TypeScript
53
star
84

terminal-portfolio

TypeScript
51
star
85

arweave-workshop

JavaScript
50
star
86

lens-gated-publications

Example application implementing gated Lens posts, encryption, and decryption
JavaScript
49
star
87

graphql-search

Implementing Search in GraphQL using AWS AppSync & React Apollo
JavaScript
49
star
88

basic-amplify-storage-example

A basic example app showing how to add storage with Amazon S3
JavaScript
49
star
89

production-ready-vue-authentication

How to implement a real user authentication flow in Vue with Vue Router & AWS Amplify.
Vue
48
star
90

build-an-authenticated-api-with-cdk

Workshop - Build an authenticated CDK back end
TypeScript
48
star
91

real-time-image-tracking

Real-time image tracking with React, GraphQL, and AWS AppSync
JavaScript
48
star
92

appsync-lambda-ai

Demo of using a GraphQL resolver to hit a lambda function, then hit a few AI services, and return the response.
JavaScript
47
star
93

appsync-react-native-with-user-authorization

End to end React Native + AWS AppSync GraphQL application with queries, mutations, subscriptions, & user authentication & authorization
JavaScript
47
star
94

openzeppelin-nft-api

Building NFT APIs with OpenZeppelin and The Graph
46
star
95

cryptocoven-api

Cryptocoven Graph API
TypeScript
46
star
96

transilator

Text translation and synthesization Chrome plugin
JavaScript
46
star
97

basic-serverless-api

A basic full stack example of building an API with AWS Amplify, Amazon API Gateway, AWS Lambda, and Amazon DynamoDB
JavaScript
46
star
98

xp-mobile-account-abstraction

TypeScript
45
star
99

react-native-navigator-experimental-redux

React Native Navigator Experimental with Redux
JavaScript
45
star
100

next.js-amplify-datastore

An example app using Amplify DataStore with Next.js for static site generation, pre-rendering, and SSR
JavaScript
45
star