In this workshop we'll learn how to build cloud-enabled mobile applications with React Native & AWS Amplify.
- Authentication
- GraphQL API with AWS AppSync
- Serverless Functions
- REST API with a Lambda Function
- Analytics
- Adding Storage with Amazon S3
- Multiple Serverless Environments
- Removing / Deleting Services
- Visit the AWS Console.
- In the top right corner, click on My Account.
- In the left menu, click Credits.
To get started, we first need to create a new React Native project & change into the new directory using the React Native CLI (See Building Projects With Native Code in the documentation) or Expo CLI.
If you already have the CLI installed, go ahead and create a new React Native app. If not, install the CLI & create a new app:
npm install -g react-native-cli
react-native init RNAmplify
# or
npm install -g expo-cli
expo init RNAmplify
> Choose a template: blank
Now change into the new app directory & install the AWS Amplify, AWS Amplify React Native, & React Native Vector Icon libraries:
cd RNAmplify
npm install --save aws-amplify [email protected] uuid
# or
yarn add aws-amplify [email protected] uuid
Finally, if you're not using Expo CLI you need to link two native libraries:
react-native link react-native-vector-icons
react-native link amazon-cognito-identity-js
Next, run the app:
react-native run-ios
# or if running android
react-native run-android
# or, if using expo
expo start
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
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
- Do you want to use an AWS profile? Y
- 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.
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.
To configure the app, open index.js and add the following code below the last import:
import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)
Now, our app is ready to start using our AWS services.
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)
- What attributes are required for signing up? Email (keep default)
Now, we'll run the push command and the cloud resources will be created in our AWS account.
amplify push
To view the new Cognito authentication service at any time after its creation, run the following command:
amplify console auth
To add authentication, we'll go into App.js and first import the withAuthenticator
HOC (Higher Order Component) from aws-amplify-react
:
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
We can access the user's info now that they are signed in by calling Auth.currentAuthenticatedUser()
.
import { Auth } from 'aws-amplify'
async componentDidMount() {
const user = await Auth.currentAuthenticatedUser()
console.log('user:', user)
}
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:
import React from 'react'
import { View, Text } from 'react-native'
import { Auth } from 'aws-amplify'
import { withAuthenticator } from 'aws-amplify-react-native'
class App extends React.Component {
signOut = () => {
Auth.signOut()
.then(() => this.props.onStateChange('signedOut'))
.catch(err => console.log('err: ', err))
}
render() {
return (
<View style={{ paddingTop: 200}}>
<Text>Hello World</Text>
<Text onPress={this.signOut}>Sign Out</Text>
</View>
)
}
}
export default withAuthenticator(App)
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)
}
}
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 an authorization type for the API API key
- Do you have an annotated GraphQL schema? N
- Do you want a guided schema creation? Y
- What best describes your project: 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, let's push the configuration to our account:
amplify push
- Do you want to generate code for your newly created GraphQL API: Y
- Choose the code generation language target: Your target preference
- 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: Y
- Enter maximum statement depth [increase from default if your schema is deeply nested]: (2)
To view the new AWS AppSync API at any time after its creation, run the following command:
amplify console api
In the AWS AppSync console, open your API & then click on Queries.
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
}
}
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.
// App.js
// imports from Amplify library
import { API, graphqlOperation } from 'aws-amplify'
// import the query
import { listRestaurants } from './src/graphql/queries'
// 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)
}
}
// add UI in render method to show data
{
this.state.restaurants.map((restaurant, index) => (
<View key={index}>
<Text>{restaurant.name}</Text>
<Text>{restaurant.description}</Text>
<Text>{restaurant.city}</Text>
</View>
))
}
Now, let's look at how we can create mutations.
// additional imports
import {
// ...existing imports
TextInput, Button
} from 'react-native'
import { graphqlOperation, API } from 'aws-amplify'
import uuid from 'uuid/v4'
const CLIENTID = uuid()
// import the mutation
import { createRestaurant } from './src/graphql/mutations'
// add name & description fields to initial state
state = {
name: '', description: '', city: '', restaurants: []
}
createRestaurant = async() => {
const { name, description, city } = this.state
const restaurant = {
name, description, city, clientId: CLIENTID
}
const restaurants = [...this.state.restaurants, restaurant]
this.setState({
restaurants,
name: '', description: '', city: ''
})
try {
await API.graphql(graphqlOperation(createRestaurant, {
input: restaurant
}))
console.log('item created!')
} catch (err) {
console.log('error creating restaurant...', err)
}
}
// change state then user types into input
onChange = (key, value) => {
this.setState({ [key]: value })
}
// add UI with event handlers to manage user input
<TextInput
onChangeText={v => this.onChange('name', v)}
value={this.state.name}
style={{ height: 50, margin: 5, backgroundColor: "#ddd" }}
/>
<TextInput
style={{ height: 50, margin: 5, backgroundColor: "#ddd" }}
onChangeText={v => this.onChange('description', v)}
value={this.state.description}
/>
<TextInput
style={{ height: 50, margin: 5, backgroundColor: "#ddd" }}
onChangeText={v => this.onChange('city', v)}
value={this.state.city}
/>
<Button onPress={this.createRestaurant} title='Create Restaurant' />
// update styles to remove alignItems property
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center',
},
});
Next, let's see how we can create a subscription to subscribe to changes of data in our API.
To do so, we need to define the subscription, listen for the subscription, & update the state whenever a new piece of data comes in through the subscription.
// import the subscription
import { onCreateRestaurant } from './src/graphql/subscriptions'
// define the subscription in the class
subscription = {}
// subscribe in componentDidMount
componentDidMount() {
this.subscription = API.graphql(
graphqlOperation(onCreateRestaurant)
).subscribe({
next: eventData => {
console.log('eventData', eventData)
const restaurant = eventData.value.data.onCreateRestaurant
if(CLIENTID === restaurant.clientId) return
const restaurants = [...this.state.restaurants, restaurant]
this.setState({ restaurants })
}
});
}
// remove the subscription in componentWillUnmount
componentWillUnmount() {
this.subscription.unsubscribe()
}
Recreate this functionality in Hooks
For direction, check out the tutorial here
For the solution to this challenge, view the hooks file.
To add a serverless function, we can run the following command:
amplify add function
Answer the following questions
- Provide a friendly name for your resource to be used as a label for this category in the project: basiclambda
- Provide the AWS Lambda function name: basiclambda
- Choose the function template that you want to use: Hello world function
- Do you want to access other resources created in this project from your Lambda function? 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 = function (event, context) {
console.log('event: ', event)
const body = {
message: "Hello world!"
}
const response = {
statusCode: 200,
body
}
context.done(null, response);
}
Next, we can test this out by running:
amplify function invoke basiclambda
- Provide the name of the script file that contains your handler function: index.js
- Provide the name of the handler function to invoke: handler
You'll notice the following output from your terminal:
Running "lambda_invoke:default" (lambda_invoke) task
event: { key1: 'value1', key2: 'value2', key3: 'value3' }
Success! Message:
------------------
{"statusCode":200,"body":{"message":"Hello world!"}}
Done.
Done running invoke function.
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.
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
Answer the following questions
- Provide a friendly name for your resource to be used as a label for this category in the project: cryptofunction
- Provide the AWS Lambda function name: cryptofunction
- Choose the function template that you want to use: Serverless express function (Integration with Amazon API Gateway)
- Do you want to access other resources created in this project from your Lambda function? N
- 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.
Here, we'll add the following code & save the file:
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 last app.use() method, add the following code π
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) {
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 }))
})
Next, we'll install axios in the function package:
cd amplify/backend/function/cryptofunction/src
npm install axios
cd ../../../../../
Next, change back into the root directory.
Now we can test this function out:
amplify function invoke cryptofunction
This will start up the node server. We can then make curl
requests agains the endpoint:
curl 'localhost:3000/coins'
If we'd like to test out the query parameters, we can update the event.json to add the following:
{
"httpMethod": "GET",
"path": "/coins",
"queryStringParameters": {
"start": "0",
"limit": "1"
}
}
When we invoke the function these query parameters will be passed in & the http request will be made immediately.
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
Answer the following questions
- 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
Now that the API is created we can start sending requests to it & interacting with it.
Let's request some data from the API:
// src/App.js
import React from 'react'
import { View, Text } 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 {
// 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}>
<Text>{c.name}</Text>
<Text>{c.price_usd}</Text>
</View>
))
}
</View>
)
}
}
export default withAuthenticator(App, { includeGreetings: true })
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
- overwrite YOURFILEPATH-cloudformation-template.yml Y
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 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))
}
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!
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
}
}
}
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
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.
To delete the entire project, run the delete
command:
amplify delete