├── .gitignore ├── README.md ├── dashboard1.jpg ├── dashboard2.jpg └── header.jpg /.gitignore: -------------------------------------------------------------------------------- 1 | amplify-web-workshop 2 | 3 | amplify-demos/.gitignore 4 | amplify-demos/amplify 5 | amplify-demos/.amplifyrc 6 | amplify-demos/src/aws-exports.js 7 | amplify-demos/node_modules -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Building Serverless Web Applications with React and AWS Amplify 2 | 3 | In this workshop we'll learn how to build cloud-enabled web applications with GraphQL, React, & [AWS Amplify](https://aws-amplify.github.io/). 4 | 5 | ![](header.jpg) 6 | 7 | ### Topics we'll be covering: 8 | 9 | - [Authentication](https://github.com/dabit3/aws-amplify-workshop-react#adding-authentication) 10 | - [GraphQL API with AWS AppSync](https://github.com/dabit3/aws-amplify-workshop-react#adding-a-graphql-api) 11 | - [Adding Authorization to the GraphQL API](https://github.com/dabit3/aws-amplify-workshop-react#adding-authorization-to-the-graphql-api) 12 | - [Serverless Functions](https://github.com/dabit3/aws-amplify-workshop-react#adding-a-serverless-function) 13 | - [REST API with a Lambda Function](https://github.com/dabit3/aws-amplify-workshop-react#adding-a-rest-api) 14 | - [Adding Storage with Amazon S3](https://github.com/dabit3/aws-amplify-workshop-react#working-with-storage) 15 | - [Analytics](https://github.com/dabit3/aws-amplify-workshop-react#adding-analytics) 16 | - [Multiple Environments](https://github.com/dabit3/aws-amplify-workshop-react#working-with-multiple-environments) 17 | - [Deploying via the Amplify Console](https://github.com/dabit3/aws-amplify-workshop-react#deploying-via-the-amplify-console) 18 | - [React Native](https://github.com/dabit3/aws-amplify-workshop-react#react-native) 19 | - [Removing / Deleting Services](https://github.com/dabit3/aws-amplify-workshop-react#removing-services) 20 | 21 | 27 | 28 | ## Getting Started - Creating the React Application 29 | 30 | To get started, we first need to create a new React project & change into the new directory using the [Create React App CLI](https://github.com/facebook/create-react-app). 31 | 32 | If you already have this installed, skip to the next step. If not, either install the CLI & create the app or create a new app using npx: 33 | 34 | ```bash 35 | npm install -g create-react-app 36 | create-react-app my-amplify-app 37 | ``` 38 | 39 | Or use npx (npm 5.2 & later) to create a new app: 40 | 41 | ```bash 42 | npx create-react-app my-amplify-app 43 | ``` 44 | 45 | Now change into the new app directory & install the AWS Amplify & AWS Amplify React libraries: 46 | 47 | ```bash 48 | cd my-amplify-app 49 | npm install --save aws-amplify aws-amplify-react uuid 50 | # or 51 | yarn add aws-amplify aws-amplify-react uuid 52 | ``` 53 | 54 | ## Installing the CLI & Initializing a new AWS Amplify Project 55 | 56 | ### Installing the CLI 57 | 58 | Next, we'll install the AWS Amplify CLI: 59 | 60 | ```bash 61 | npm install -g @aws-amplify/cli 62 | ``` 63 | 64 | Now we need to configure the CLI with our credentials: 65 | 66 | ```js 67 | amplify configure 68 | ``` 69 | 70 | > If you'd like to see a video walkthrough of this configuration process, click [here](https://www.youtube.com/watch?v=fWbM5DLh25U). 71 | 72 | Here we'll walk through the `amplify configure` setup. Once you've signed in to the AWS console, continue: 73 | - Specify the AWS Region: __eu-central-1__ 74 | - Specify the username of the new IAM user: __amplify-workshop-user__ 75 | > 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. 76 | - Enter the access key of the newly created user: 77 | accessKeyId: __()__ 78 | secretAccessKey: __()__ 79 | - Profile Name: __amplify-workshop-user__ 80 | 81 | ### Initializing A New Project 82 | 83 | ```bash 84 | amplify init 85 | ``` 86 | 87 | - Enter a name for the project: __amplifyreactapp__ 88 | - Enter a name for the environment: __dev__ 89 | - Choose your default editor: __Visual Studio Code (or your default editor)__ 90 | - Please choose the type of app that you're building __javascript__ 91 | - What javascript framework are you using __react__ 92 | - Source Directory Path: __src__ 93 | - Distribution Directory Path: __build__ 94 | - Build Command: __npm run-script build__ 95 | - Start Command: __npm run-script start__ 96 | - Do you want to use an AWS profile? __Y__ 97 | - Please choose the profile you want to use: __amplify-workshop-user__ 98 | 99 | Now, the AWS Amplify CLI has iniatilized a new project & you will see a new folder: __amplify__ & a new file called `aws-exports.js` in the __src__ directory. These files hold your project configuration. 100 | 101 | ## Adding Authentication 102 | 103 | To add authentication, we can use the following command: 104 | 105 | ```sh 106 | amplify add auth 107 | ``` 108 | - Do you want to use default authentication and security configuration? __Default configuration__ 109 | - How do you want users to be able to sign in when using your Cognito User Pool? __Username__ 110 | - What attributes are required for signing up? __Email__ (keep default) 111 | 112 | Now, we'll run the push command and the cloud resources will be created in our AWS account. 113 | 114 | ```bash 115 | amplify push 116 | ``` 117 | 118 | To view the service you can run the `console` command the feature you'd like to view: 119 | 120 | ```sh 121 | amplify console auth 122 | ``` 123 | 124 | ### Configuring the React applicaion 125 | 126 | Now, our resources are created & we can start using them! 127 | 128 | The first thing we need to do is to configure our React 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 src folder. 129 | 130 | To configure the app, open __src/index.js__ and add the following code below the last import: 131 | 132 | ```js 133 | import Amplify from 'aws-amplify' 134 | import config from './aws-exports' 135 | Amplify.configure(config) 136 | ``` 137 | 138 | Now, our app is ready to start using our AWS services. 139 | 140 | ### Using the withAuthenticator component 141 | 142 | To add authentication, we'll go into __src/App.js__ and first import the `withAuthenticator` HOC (Higher Order Component) from `aws-amplify-react`: 143 | 144 | ### src/App.js 145 | 146 | ```js 147 | import { withAuthenticator } from 'aws-amplify-react' 148 | ``` 149 | 150 | Next, we'll wrap our default export (the App component) with the `withAuthenticator` HOC: 151 | 152 | ```js 153 | export default withAuthenticator(App, { includeGreetings: true }) 154 | ``` 155 | 156 | ```sh 157 | # run the app 158 | 159 | npm start 160 | ``` 161 | 162 | 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. 163 | 164 | > To view the new user that was created in Cognito, go back to the dashboard at [https://console.aws.amazon.com/cognito/](https://console.aws.amazon.com/cognito/). Also be sure that your region is set correctly. 165 | 166 | ### Accessing User Data 167 | 168 | We can access the user's info now that they are signed in by calling `Auth.currentAuthenticatedUser()`. 169 | 170 | ### src/App.js 171 | 172 | ```js 173 | import React, { useEffect } from 'react' 174 | import { Auth } from 'aws-amplify' 175 | 176 | function App() { 177 | useEffect(() => { 178 | Auth.currentAuthenticatedUser() 179 | .then(user => console.log({ user })) 180 | .catch(error => console.log({ error })) 181 | }) 182 | return ( 183 |
184 |

185 | Edit src/App.js and save to reload. 186 |

187 |
188 | ) 189 | } 190 | 191 | export default App 192 | ``` 193 | 194 | ### Custom authentication strategies 195 | 196 | 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. 197 | 198 | Let's look at how we might create our own authentication flow. 199 | 200 | 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 4 user inputs to capture the user's username, email, password, & phone number. 201 | 202 | To do this, we could create some initial state for these values & create an event handler that we could attach to the form inputs: 203 | 204 | ```js 205 | // initial state 206 | import React, { useReducer } from 'react' 207 | 208 | // define initial state 209 | const initialState = { 210 | username: '', password: '', email: '' 211 | } 212 | 213 | // create reducer 214 | function reducer(state, action) { 215 | switch(action.type) { 216 | case 'SET_INPUT': 217 | return { ...state, [action.inputName]: action.inputValue } 218 | default: 219 | return state 220 | } 221 | } 222 | 223 | // useReducer hook creates local state 224 | const [state, dispatch] = useReducer(reducer, initialState) 225 | 226 | // event handler 227 | function onChange(e) { 228 | dispatch({ 229 | type: 'SET_INPUT', 230 | inputName: e.target.name, 231 | inputValue: e.target.value 232 | }) 233 | } 234 | 235 | // example of usage with input 236 | 242 | ``` 243 | 244 | We'd also need to have a method that signed up & signed in users. We can use the Auth class to do this. The Auth class has over 30 methods including things like `signUp`, `signIn`, `confirmSignUp`, `confirmSignIn`, & `forgotPassword`. These functions return a promise so they need to be handled asynchronously. 245 | 246 | ```js 247 | // import the Auth component 248 | import { Auth } from 'aws-amplify' 249 | 250 | // Class method to sign up a user 251 | async function signUp() { 252 | const { username, password, email } = state 253 | try { 254 | await Auth.signUp({ username, password, attributes: { email }}) 255 | console.log('user successfully signed up!') 256 | } catch (err) { 257 | console.log('error signing up user...', err) 258 | } 259 | } 260 | 261 | 262 | ``` 263 | 264 | ## Adding a GraphQL API 265 | 266 | To add a GraphQL API, we can use the following command: 267 | 268 | ```sh 269 | amplify add api 270 | ``` 271 | 272 | Answer the following questions 273 | 274 | - Please select from one of the above mentioned services __GraphQL__ 275 | - Provide API name: __CryptoGraphQL__ 276 | - Choose an authorization type for the API __API key__ 277 | - Do you have an annotated GraphQL schema? __N__ 278 | - Do you want a guided schema creation? __Y__ 279 | - What best describes your project: __Single object with fields (e.g. “Todo” with ID, name, description)__ 280 | - Do you want to edit the schema now? (Y/n) __Y__ 281 | 282 | > When prompted, update the schema to the following: 283 | 284 | ```graphql 285 | type Coin @model { 286 | id: ID! 287 | clientId: ID 288 | name: String! 289 | symbol: String! 290 | price: Float! 291 | } 292 | ``` 293 | 294 | > Next, let's push the configuration to our account: 295 | 296 | ```bash 297 | amplify push 298 | ``` 299 | 300 | - Do you want to generate code for your newly created GraphQL API __Y__ 301 | - Choose the code generation language target: __javascript__ 302 | - Enter the file name pattern of graphql queries, mutations and subscriptions: __(src/graphql/**/*.js)__ 303 | - Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions? __Y__ 304 | - Enter maximum statement depth [increase from default if your schema is deeply nested] __2__ 305 | 306 | To view the service you can run the `console` command the feature you'd like to view: 307 | 308 | ```sh 309 | amplify console api 310 | ``` 311 | 312 | ### Adding mutations from within the AWS AppSync Console 313 | 314 | In the AWS AppSync console, open your API & then click on Queries. 315 | 316 | Execute the following mutation to create a new coin in the API: 317 | 318 | ```graphql 319 | mutation createCoin { 320 | createCoin(input: { 321 | name: "Bitcoin" 322 | symbol: "BTC" 323 | price: 9000 324 | }) { 325 | id name symbol price 326 | } 327 | } 328 | ``` 329 | 330 | Now, let's query for the coin: 331 | 332 | ```graphql 333 | query listCoins { 334 | listCoins { 335 | items { 336 | id 337 | name 338 | symbol 339 | price 340 | } 341 | } 342 | } 343 | ``` 344 | 345 | We can even add search / filter capabilities when querying: 346 | 347 | ```graphql 348 | query listCoins { 349 | listCoins(filter: { 350 | price: { 351 | gt: 2000 352 | } 353 | }) { 354 | items { 355 | id 356 | name 357 | symbol 358 | price 359 | } 360 | } 361 | } 362 | ``` 363 | 364 | ### Interacting with the GraphQL API from our client application - Querying for data 365 | 366 | Now that the GraphQL API is created we can begin interacting with it! 367 | 368 | The first thing we'll do is perform a query to fetch data from our API. 369 | 370 | 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. 371 | 372 | ### src/App.js 373 | 374 | ```js 375 | // src/App.js 376 | import React, { useEffect, useState } from 'react' 377 | 378 | // imports from Amplify library 379 | import { API, graphqlOperation } from 'aws-amplify' 380 | import { withAuthenticator } from 'aws-amplify-react' 381 | 382 | // import query 383 | import { listCoins } from './graphql/queries' 384 | 385 | function App() { 386 | const [coins, updateCoins] = useState([]) 387 | 388 | useEffect(() => { 389 | getData() 390 | }, []) 391 | 392 | async function getData() { 393 | try { 394 | const coinData = await API.graphql(graphqlOperation(listCoins)) 395 | console.log('data from API: ', coinData) 396 | updateCoins(coinData.data.listCoins.items) 397 | } catch (err) { 398 | console.log('error fetching data..', err) 399 | } 400 | } 401 | 402 | return ( 403 |
404 | { 405 | coins.map((c, i) => ( 406 |
407 |

{c.name}

408 |

{c.symbol}

409 |

{c.price}

410 |
411 | )) 412 | } 413 |
414 | ) 415 | } 416 | 417 | export default withAuthenticator(App, { includeGreetings: true }) 418 | ``` 419 | 420 | ## Performing mutations 421 | 422 | Now, let's look at how we can create mutations. Let's change the component to use a `useReducer` hook. 423 | 424 | ```js 425 | // src/App.js 426 | import React, { useEffect, useReducer } from 'react' 427 | import { API, graphqlOperation } from 'aws-amplify' 428 | import { withAuthenticator } from 'aws-amplify-react' 429 | import { listCoins } from './graphql/queries' 430 | import { createCoin as CreateCoin } from './graphql/mutations' 431 | 432 | // import uuid to create a unique client ID 433 | import uuid from 'uuid/v4' 434 | 435 | const CLIENT_ID = uuid() 436 | 437 | // create initial state 438 | const initialState = { 439 | name: '', price: '', symbol: '', coins: [] 440 | } 441 | 442 | // create reducer to update state 443 | function reducer(state, action) { 444 | switch(action.type) { 445 | case 'SETCOINS': 446 | return { ...state, coins: action.coins } 447 | case 'SETINPUT': 448 | return { ...state, [action.key]: action.value } 449 | default: 450 | return state 451 | } 452 | } 453 | 454 | function App() { 455 | const [state, dispatch] = useReducer(reducer, initialState) 456 | 457 | useEffect(() => { 458 | getData() 459 | }, []) 460 | 461 | async function getData() { 462 | try { 463 | const coinData = await API.graphql(graphqlOperation(listCoins)) 464 | console.log('data from API: ', coinData) 465 | dispatch({ type: 'SETCOINS', coins: coinData.data.listCoins.items}) 466 | } catch (err) { 467 | console.log('error fetching data..', err) 468 | } 469 | } 470 | 471 | async function createCoin() { 472 | const { name, price, symbol } = state 473 | if (name === '' || price === '' || symbol === '') return 474 | const coin = { 475 | name, price: parseFloat(price), symbol, clientId: CLIENT_ID 476 | } 477 | const coins = [...state.coins, coin] 478 | dispatch({ type: 'SETCOINS', coins }) 479 | console.log('coin:', coin) 480 | 481 | try { 482 | await API.graphql(graphqlOperation(CreateCoin, { input: coin })) 483 | console.log('item created!') 484 | } catch (err) { 485 | console.log('error creating coin...', err) 486 | } 487 | } 488 | 489 | // change state then user types into input 490 | function onChange(e) { 491 | dispatch({ type: 'SETINPUT', key: e.target.name, value: e.target.value }) 492 | } 493 | 494 | // add UI with event handlers to manage user input 495 | return ( 496 |
497 | 503 | 509 | 515 | 516 | { 517 | state.coins.map((c, i) => ( 518 |
519 |

{c.name}

520 |

{c.symbol}

521 |

{c.price}

522 |
523 | )) 524 | } 525 |
526 | ) 527 | } 528 | 529 | export default withAuthenticator(App, { includeGreetings: true }) 530 | ``` 531 | 532 | ### GraphQL Subscriptions 533 | 534 | Next, let's see how we can create a subscription to subscribe to changes of data in our API. 535 | 536 | 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. 537 | 538 | ```js 539 | // import the subscription 540 | import { onCreateCoin } from './graphql/subscriptions' 541 | 542 | // update reducer 543 | function reducer(state, action) { 544 | switch(action.type) { 545 | case 'SETCOINS': 546 | return { ...state, coins: action.coins } 547 | case 'SETINPUT': 548 | return { ...state, [action.key]: action.value } 549 | // new 👇 550 | case 'ADDCOIN': 551 | return { ...state, coins: [...state.coins, action.coin] } 552 | default: 553 | return state 554 | } 555 | } 556 | 557 | // subscribe in useEffect 558 | useEffect(() => { 559 | const subscription = API.graphql(graphqlOperation(onCreateCoin)).subscribe({ 560 | next: (eventData) => { 561 | const coin = eventData.value.data.onCreateCoin 562 | if (coin.clientId === CLIENT_ID) return 563 | dispatch({ type: 'ADDCOIN', coin }) 564 | } 565 | }) 566 | return () => subscription.unsubscribe() 567 | }, []) 568 | ``` 569 | 570 | ## Adding Authorization to the GraphQL API 571 | 572 | To add authorization to the API, we can re-configure the API to use our cognito identity pool. To do so, we can run `amplify configure api`: 573 | 574 | ```sh 575 | amplify configure api 576 | ``` 577 | 578 | - Please select from one of the below mentioned services: __GraphQL__ 579 | - Choose an authorization type for the API: __Amazon Cognito User Pool__ 580 | 581 | Next, we'll run `amplify push`: 582 | 583 | ```sh 584 | amplify push 585 | ``` 586 | 587 | - Do you want to update code for your updated GraphQL API __N__ 588 | 589 | Now, we can only access the API with a logged in user. 590 | 591 | ### Adding fine-grained access controls to the GraphQL API 592 | 593 | Next, let's add a field that can only be accessed by the current user. 594 | 595 | To do so, we'll update the schema to add the following new type below the existing Coin type: 596 | 597 | ```graphql 598 | type Note @model @auth(rules: [{allow: owner}]) { 599 | id: ID! 600 | title: String! 601 | description: String 602 | } 603 | ``` 604 | 605 | Next, we'll deploy the updates to our API: 606 | 607 | ```sh 608 | amplify push 609 | ``` 610 | 611 | - Do you want to update code for your updated GraphQL API: __Y__ 612 | - Do you want to generate GraphQL statements (queries, mutations and subscription) based on your schema types? __Y__ 613 | 614 | Now, the operations associated with this field will only be accessible by the creator of the item. 615 | 616 | To test it out, try creating a new user & accessing a note from another user. 617 | 618 | To test the API out in the AWS AppSync console, it will ask for you to __Login with User Pools__. The form will ask you for a __ClientId__. This __ClientId__ is located in __src/aws-exports.js__ in the `aws_user_pools_web_client_id` field. 619 | 620 | ## Adding a Serverless Function 621 | 622 | ### Adding a basic Lambda Function 623 | 624 | To add a serverless function, we can run the following command: 625 | 626 | ```sh 627 | amplify add function 628 | ``` 629 | 630 | > Answer the following questions 631 | 632 | - Provide a friendly name for your resource to be used as a label for this category in the project: __basiclambda__ 633 | - Provide the AWS Lambda function name: __basiclambda__ 634 | - Choose the function template that you want to use: __Hello world function__ 635 | - Do you want to access other resources created in this project from your Lambda function? __No__ 636 | - Do you want to edit the local lambda function now? __Y__ 637 | 638 | > This should open the function package located at __amplify/backend/function/basiclambda/src/index.js__. 639 | 640 | Edit the function to look like this, & then save the file. 641 | 642 | ```js 643 | exports.handler = function (event, context) { 644 | console.log('event: ', event) 645 | const body = { 646 | message: "Hello world!" 647 | } 648 | const response = { 649 | statusCode: 200, 650 | body 651 | } 652 | context.done(null, response); 653 | } 654 | ``` 655 | 656 | Next, we can test this out by running: 657 | 658 | ```sh 659 | amplify function invoke basiclambda 660 | ``` 661 | 662 | Using service: Lambda, provided by: awscloudformation 663 | - Provide the name of the script file that contains your handler function: __index.js__ 664 | - Provide the name of the handler function to invoke: __handler__ 665 | 666 | You'll notice the following output from your terminal: 667 | 668 | ```sh 669 | Running "lambda_invoke:default" (lambda_invoke) task 670 | 671 | event: { key1: 'value1', key2: 'value2', key3: 'value3' } 672 | 673 | Success! Message: 674 | ------------------ 675 | {"statusCode":200,"body":{"message":"Hello world!"}} 676 | 677 | Done. 678 | Done running invoke function. 679 | ``` 680 | 681 | _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._ 682 | 683 | Feel free to test out the function by updating `event.json` with data of your own. 684 | 685 | ### Adding a function running an express server 686 | 687 | Next, we'll build a function that will be running an [Express](https://expressjs.com/) server inside of it. 688 | 689 | This new function will fetch data from a cryptocurrency API & return the values in the response. 690 | 691 | To get started, we'll create a new function: 692 | 693 | ```sh 694 | amplify add function 695 | ``` 696 | 697 | > Answer the following questions 698 | 699 | - Provide a friendly name for your resource to be used as a label for this category in the project: __cryptofunction__ 700 | - Provide the AWS Lambda function name: __cryptofunction__ 701 | - Choose the function template that you want to use: __Serverless express function (Integration with Amazon API Gateway)__ 702 | - Do you want to access other resources created in this project from your Lambda function? __No__ 703 | - Do you want to edit the local lambda function now? __Y__ 704 | 705 | > This should open the function package located at __amplify/backend/function/cryptofunction/src/index.js__. 706 | 707 | Here, we'll add the following code & save the file: 708 | 709 | ```js 710 | app.use(function(req, res, next) { 711 | res.header("Access-Control-Allow-Origin", "*") 712 | res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") 713 | next() 714 | }); 715 | // below the last app.use() method, add the following code 👇 716 | const axios = require('axios') 717 | 718 | app.get('/coins', function(req, res) { 719 | let apiUrl = `https://api.coinlore.com/api/tickers?start=0&limit=10` 720 | 721 | console.log(req.query); 722 | if (req && req.query) { 723 | const { start = 0, limit = 10 } = req.query 724 | apiUrl = `https://api.coinlore.com/api/tickers/?start=${start}&limit=${limit}` 725 | } 726 | axios.get(apiUrl) 727 | .then(response => { 728 | res.json({ 729 | coins: response.data.data 730 | }) 731 | }) 732 | .catch(err => res.json({ error: err })) 733 | }) 734 | ``` 735 | 736 | Next, we'll install axios in the function package: 737 | 738 | ```sh 739 | cd amplify/backend/function/cryptofunction/src 740 | 741 | npm install axios 742 | ``` 743 | 744 | Next, change back into the root directory. 745 | 746 | Now we can test this function out: 747 | 748 | ```sh 749 | amplify function build 750 | amplify function invoke cryptofunction 751 | ``` 752 | 753 | This will start up the node server. We can then make `curl` requests agains the endpoint: 754 | 755 | ```sh 756 | curl 'localhost:3000/coins?start=0&limit=1' 757 | ``` 758 | 759 | If we'd like to test out the query parameters, we can update the __event.json__ to add the following: 760 | 761 | ```json 762 | { 763 | "httpMethod": "GET", 764 | "path": "/coins", 765 | "query": { 766 | "start": "0", 767 | "limit": "1" 768 | } 769 | } 770 | ``` 771 | 772 | When we invoke the function these query parameters will be passed in & the http request will be made immediately. 773 | 774 | ## Adding a REST API 775 | 776 | Now that we've created the cryptocurrency Lambda function let's add an API endpoint so we can invoke it via http. 777 | 778 | To add the REST API, we can use the following command: 779 | 780 | ```sh 781 | amplify add api 782 | ``` 783 | 784 | > Answer the following questions 785 | 786 | - Please select from one of the above mentioned services __REST__ 787 | - Provide a friendly name for your resource that will be used to label this category in the project: __cryptoapi__ 788 | - Provide a path (e.g., /items) __/coins__ 789 | - Choose lambda source __Use a Lambda function already added in the current Amplify project__ 790 | - Choose the Lambda function to invoke by this path: __cryptofunction__ 791 | - Restrict API access __Y__ 792 | - Who should have access? __Authenticated users only__ 793 | - What kind of access do you want for Authenticated users __read/create/update/delete__ 794 | - Do you want to add another path? (y/N) __N__ 795 | 796 | Now the resources have been created & configured & we can push them to our account: 797 | 798 | ```bash 799 | amplify push 800 | ``` 801 | 802 | ### Interacting with the new API 803 | 804 | Now that the API is created we can start sending requests to it & interacting with it. 805 | 806 | Let's request some data from the API: 807 | 808 | ```js 809 | // src/App.js 810 | import React, { useEffect, useState } from 'react' 811 | import { API } from 'aws-amplify' 812 | import { withAuthenticator } from 'aws-amplify-react' 813 | 814 | function App() { 815 | const [coins, updateCoins] = useState([]) 816 | 817 | async function getData() { 818 | try { 819 | // const data = await API.get('cryptoapi', '/coins') 820 | const data = await API.get('cryptoapi', '/coins?limit=5&start=100') 821 | console.log('data from Lambda REST API: ', data) 822 | updateCoins(data.coins) 823 | } catch (err) { 824 | console.log('error fetching data..', err) 825 | } 826 | } 827 | 828 | useEffect(() => { 829 | getData() 830 | }, []) 831 | 832 | return ( 833 |
834 | { 835 | coins.map((c, i) => ( 836 |
837 |

{c.name}

838 |

{c.price_usd}

839 |
840 | )) 841 | } 842 |
843 | ) 844 | } 845 | 846 | export default withAuthenticator(App, { includeGreetings: true }) 847 | ``` 848 | 849 | #### Challenge 850 | 851 | Refactor the above component to use `useReducer` instead of `useState` to add an additional `loading` parameter to the initial state to indicate that the app is fetching and loading when launched. 852 | 853 | ## Working with Storage 854 | 855 | To add storage, we can use the following command: 856 | 857 | ```sh 858 | amplify add storage 859 | ``` 860 | 861 | > Answer the following questions 862 | 863 | - Please select from one of the below mentioned services __Content (Images, audio, video, etc.)__ 864 | - Please provide a friendly name for your resource that will be used to label this category in the 865 | project: __YOURAPINAME__ 866 | - Please provide bucket name: __YOURUNIQUEBUCKETNAME__ 867 | - Who should have access: __Auth users only__ 868 | - What kind of access do you want for Authenticated users __create/update, read, delete__ 869 | 870 | 871 | ```sh 872 | amplify push 873 | ``` 874 | 875 | Now, storage is configured & ready to use. 876 | 877 | What we've done above is created configured an Amazon S3 bucket that we can now start using for storing items. 878 | 879 | For example, if we wanted to test it out we could store some text in a file like this: 880 | 881 | ```js 882 | import { Storage } from 'aws-amplify' 883 | 884 | // create function to work with Storage 885 | function addToStorage() { 886 | await Storage.put('javascript/MyReactComponent.js', ` 887 | import React from 'react' 888 | const App = () => ( 889 |

Hello World

890 | ) 891 | export default App 892 | `) 893 | console.log('data stored in S3!') 894 | } 895 | 896 | // add click handler 897 | 898 | ``` 899 | 900 | This would create a folder called `javascript` in our S3 bucket & store a file called __MyReactComponent.js__ there with the code we specified in the second argument of `Storage.put`. 901 | 902 | > To view the new bucket that was created in S3, go to the dashboard at [https://console.aws.amazon.com/s3](https://console.aws.amazon.com/s3). Also be sure that your region is set correctly. 903 | 904 | If we want to read everything from this folder, we can use `Storage.list`: 905 | 906 | ```js 907 | readFromStorage() { 908 | const data = Storage.list('javascript/') 909 | console.log('data from S3: ', data) 910 | } 911 | ``` 912 | 913 | If we only want to read the single file, we can use `Storage.get`: 914 | 915 | ```js 916 | readFromStorage() { 917 | const data = Storage.get('javascript/MyReactComponent.js') 918 | console.log('data from S3: ', data) 919 | } 920 | ``` 921 | 922 | If we wanted to pull down everything, we can use `Storage.list`: 923 | 924 | ```js 925 | function readFromStorage() { 926 | const data = Storage.list('') 927 | console.log('data from S3: ', data) 928 | } 929 | ``` 930 | 931 | ### Working with images 932 | 933 | Here's how you can store an image: 934 | 935 | ```js 936 | function App() { 937 | async function onChange(e) { 938 | const file = e.target.files[0]; 939 | await Storage.put('example.png', file) 940 | console.log('image successfully stored!') 941 | } 942 | 943 | return ( 944 | this.onChange(e)} 947 | /> 948 | ) 949 | } 950 | ``` 951 | 952 | Here's how you can read and display an image: 953 | 954 | ```js 955 | import React, { useState } from 'react' 956 | 957 | function App() { 958 | const [imageUrl, updateImage] = useState('') 959 | 960 | async function fetchImage() { 961 | const imagePath = await Storage.get('example.png') 962 | updateImage(imagePath) 963 | } 964 | 965 | return ( 966 |
967 | 968 | 969 |
970 | ) 971 | } 972 | ``` 973 | 974 | We can even use the S3Album component, one of a few components in the AWS Amplify React library to create a pre-configured photo picker: 975 | 976 | ```js 977 | import { S3Album, withAuthenticator } from 'aws-amplify-react' 978 | 979 | function App() { 980 | return ( 981 |
982 | 983 |
984 | ); 985 | } 986 | ``` 987 | 988 | ## Adding Analytics 989 | 990 | To add analytics, we can use the following command: 991 | 992 | ```sh 993 | amplify add analytics 994 | ``` 995 | 996 | > Next, we'll be prompted for the following: 997 | 998 | - Provide your pinpoint resource name: __amplifyanalytics__ 999 | - Apps need authorization to send analytics events. Do you want to allow guest/unauthenticated users to send analytics events (recommended when getting started)? __Y__ 1000 | - overwrite YOURFILEPATH-cloudformation-template.yml __Y__ 1001 | 1002 | ### Recording events 1003 | 1004 | Now that the service has been created we can now begin recording events. 1005 | 1006 | To record analytics events, we need to import the `Analytics` class from Amplify & then call `Analytics.record`: 1007 | 1008 | ```js 1009 | import { Analytics } from 'aws-amplify' 1010 | 1011 | state = {username: ''} 1012 | 1013 | async componentDidMount() { 1014 | try { 1015 | const user = await Auth.currentAuthenticatedUser() 1016 | this.setState({ username: user.username }) 1017 | } catch (err) { 1018 | console.log('error getting user: ', err) 1019 | } 1020 | } 1021 | 1022 | recordEvent = () => { 1023 | Analytics.record({ 1024 | name: 'My test event', 1025 | attributes: { 1026 | username: this.state.username 1027 | } 1028 | }) 1029 | } 1030 | 1031 | 1032 | ``` 1033 | 1034 | ## Working with multiple environments 1035 | 1036 | You can create multiple environments for your application in which to create & test out new features without affecting the main environment which you are working on. 1037 | 1038 | When you create a new environment from an existing environment, you are given a copy of the entire backend application stack from the original project. When you make changes in the new environment, you are then able to test these new changes in the new environment & merge only the changes that have been made since the new environment was created back into the original environment. 1039 | 1040 | Let's take a look at how to create a new environment. In this new environment, we'll re-configure the GraphQL Schema to have another field for the coin rank. 1041 | 1042 | First, we'll initialize a new environment using `amplify env add`: 1043 | 1044 | ```sh 1045 | amplify env add 1046 | 1047 | > Do you want to use an existing environment? No 1048 | > Enter a name for the environment: apiupdate 1049 | > Do you want to use an AWS profile? Y 1050 | > Please choose the profile you want to use: amplify-workshop-profile 1051 | ``` 1052 | 1053 | Once the new environment is initialized, we should be able to see some information about our environment setup by running: 1054 | 1055 | ```sh 1056 | amplify env list 1057 | 1058 | | Environments | 1059 | | ------------ | 1060 | | dev | 1061 | | *apiupdate | 1062 | ``` 1063 | 1064 | Now we can update the GraphQL Schema in `amplify/backend/api/CryptoGraphQL/schema.graphql` to the following (adding the `rank` field): 1065 | 1066 | ```graphql 1067 | type Coin { 1068 | id: ID! 1069 | clientId: ID 1070 | name: String! 1071 | symbol: String! 1072 | price: Float! 1073 | rank: Int 1074 | } 1075 | ``` 1076 | 1077 | Now, we can create this new stack by running `amplify push`: 1078 | 1079 | ```sh 1080 | amplify push 1081 | ``` 1082 | 1083 | After we test it out, we can now merge it into our original local environment: 1084 | 1085 | ```sh 1086 | amplify env checkout local 1087 | ``` 1088 | 1089 | Next, run the `status` command: 1090 | 1091 | ```sh 1092 | amplify status 1093 | ``` 1094 | 1095 | You should now see an __Update__ operation: 1096 | 1097 | ```sh 1098 | Current Environment: local 1099 | 1100 | | Category | Resource name | Operation | Provider plugin | 1101 | | -------- | --------------- | --------- | ----------------- | 1102 | | Api | CryptoGraphQL | Update | awscloudformation | 1103 | | Auth | cognito75a8ccb4 | No Change | awscloudformation | 1104 | ``` 1105 | 1106 | To deploy the changes, run the push command: 1107 | 1108 | ```sh 1109 | amplify push 1110 | ``` 1111 | 1112 | - Do you want to update code for your updated GraphQL API? __Y__ 1113 | - Do you want to generate GraphQL statements? __Y__ 1114 | 1115 | Now, the changes have been deployed & we can delete the apiupdate environment: 1116 | 1117 | ```sh 1118 | amplify env remove apiupdate 1119 | 1120 | Do you also want to remove all the resources of the environment from the cloud? Y 1121 | ``` 1122 | 1123 | Now, we should be able to run the `list` command & see only our main environment: 1124 | 1125 | ```sh 1126 | amplify env list 1127 | ``` 1128 | 1129 | ## Deploying via the Amplify Console 1130 | 1131 | For hosting, we can use the [Amplify Console](https://aws.amazon.com/amplify/console/) to deploy the application. 1132 | 1133 | The first thing we need to do is [create a new GitHub repo](https://github.com/new) for this project. Once we've created the repo, we'll copy the URL for the project to the clipboard & initialize git in our local project: 1134 | 1135 | ```sh 1136 | git init 1137 | 1138 | git remote add origin git@github.com:username/project-name.git 1139 | 1140 | git add . 1141 | 1142 | git commit -m 'initial commit' 1143 | 1144 | git push origin master 1145 | ``` 1146 | 1147 | Next we'll visit the Amplify Console in our AWS account at [https://eu-west-1.console.aws.amazon.com/amplify/home](https://eu-west-1.console.aws.amazon.com/amplify/home). 1148 | 1149 | Here, we'll click __Get Started__ to create a new deployment. Next, authorize Github as the repository service. 1150 | 1151 | Next, we'll choose the new repository & branch for the project we just created & click __Next__. 1152 | 1153 | In the next screen, we'll create a new role & use this role to allow the Amplify Console to deploy these resources & click __Next__. 1154 | 1155 | Finally, we can click __Save and Deploy__ to deploy our application! 1156 | 1157 | Now, we can push updates to Master to update our application. 1158 | 1159 | ## React Native 1160 | 1161 | AWS Amplify also has framework support for [React Native](https://aws-amplify.github.io/docs/js/start?platform=react-native). 1162 | 1163 | To get started with using AWS Amplify with React Native, we'll need to install the __AWS Amplify React Native__ package & then link the dependencies. 1164 | 1165 | ```sh 1166 | npm install aws-amplify-react-native 1167 | 1168 | # If using Expo, you do not need to link these two libraries as they are both part of the Expo SDK. 1169 | react-native link amazon-cognito-identity-js 1170 | react-native link react-native-vector-icons 1171 | ``` 1172 | 1173 | Implementing features with AWS Amplify in React Native is the same as the features implemented in the other steps of this workshop. The only difference is that you will be working with React Native primitives vs HTML elements. 1174 | 1175 | ## Removing Services 1176 | 1177 | 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: 1178 | 1179 | ```sh 1180 | amplify remove auth 1181 | 1182 | amplify push 1183 | ``` 1184 | 1185 | If you are unsure of what services you have enabled at any time, you can run the `amplify status` command: 1186 | 1187 | ```sh 1188 | amplify status 1189 | ``` 1190 | 1191 | `amplify status` will give you the list of resources that are currently enabled in your app. 1192 | 1193 | ## Deleting entire project 1194 | 1195 | ```sh 1196 | amplify delete 1197 | ``` 1198 | -------------------------------------------------------------------------------- /dashboard1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/aws-amplify-workshop-react/58cc0a04f3a0f6e7d17f486b3454779048278582/dashboard1.jpg -------------------------------------------------------------------------------- /dashboard2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/aws-amplify-workshop-react/58cc0a04f3a0f6e7d17f486b3454779048278582/dashboard2.jpg -------------------------------------------------------------------------------- /header.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/aws-amplify-workshop-react/58cc0a04f3a0f6e7d17f486b3454779048278582/header.jpg --------------------------------------------------------------------------------