{"id":13531609,"url":"https://github.com/dabit3/aws-appsync-react-workshop","last_synced_at":"2025-11-17T15:09:52.103Z","repository":{"id":51156532,"uuid":"174150370","full_name":"dabit3/aws-appsync-react-workshop","owner":"dabit3","description":"Building real-time offline-ready Applications with React, GraphQL \u0026 AWS AppSync","archived":false,"fork":false,"pushed_at":"2020-08-04T18:12:46.000Z","size":855,"stargazers_count":232,"open_issues_count":4,"forks_count":57,"subscribers_count":9,"default_branch":"with-testing","last_synced_at":"2025-10-14T19:08:04.132Z","etag":null,"topics":["aws-amplify","aws-appsync","graphql","graphql-api","react","serverless"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dabit3.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-03-06T13:27:55.000Z","updated_at":"2025-02-24T12:54:51.000Z","dependencies_parsed_at":"2022-09-06T02:01:17.083Z","dependency_job_id":null,"html_url":"https://github.com/dabit3/aws-appsync-react-workshop","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/dabit3/aws-appsync-react-workshop","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Faws-appsync-react-workshop","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Faws-appsync-react-workshop/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Faws-appsync-react-workshop/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Faws-appsync-react-workshop/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dabit3","download_url":"https://codeload.github.com/dabit3/aws-appsync-react-workshop/tar.gz/refs/heads/with-testing","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Faws-appsync-react-workshop/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279020645,"owners_count":26086895,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-14T02:00:06.444Z","response_time":60,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws-amplify","aws-appsync","graphql","graphql-api","react","serverless"],"created_at":"2024-08-01T07:01:04.313Z","updated_at":"2025-10-14T19:09:17.367Z","avatar_url":"https://github.com/dabit3.png","language":"JavaScript","readme":"# Building real-time applications with React, GraphQL \u0026 AWS AppSync\n\nIn this workshop we'll learn how to build cloud-enabled web applications with React, [AppSync](https://aws.amazon.com/appsync/), GraphQL, \u0026 [AWS Amplify](https://aws-amplify.github.io/).\n\n![](./appsync_header.jpg)\n\n### Topics we'll be covering:\n\n- [GraphQL API with AWS AppSync](https://github.com/dabit3/aws-appsync-react-workshop#adding-a-graphql-api)\n- [Mocking and Testing](https://github.com/dabit3/aws-appsync-react-workshop#local-mocking-and-testing)\n- [Authentication](https://github.com/dabit3/aws-appsync-react-workshop#adding-authentication)\n- [Adding Authorization to the AWS AppSync API](https://github.com/dabit3/aws-appsync-react-workshop#adding-authorization-to-the-graphql-api)\n- [Lambda Resolvers](https://github.com/dabit3/aws-appsync-react-workshop#lambda-graphql-resolvers)\n- [Deploying the Services](https://github.com/dabit3/aws-appsync-react-workshop#deploying-the-services)\n- [Hosting with the Amplify Console](https://github.com/dabit3/aws-appsync-react-workshop#hosting-via-the-amplify-console)\n- [Amplify DataStore](https://github.com/dabit3/aws-appsync-react-workshop#amplify-datastore)\n- [Deleting the resources](https://github.com/dabit3/aws-appsync-react-workshop#removing-services)\n\n## Redeeming the AWS Credit   \n\n1. Visit the [AWS Console](https://console.aws.amazon.com/console).\n2. In the top right corner, click on __My Account__.\n![](dashboard1.jpg)\n3. In the left menu, click __Credits__.\n![](dashboard2.jpg)\n\n## Getting Started - Creating the React Application\n\nTo get started, we first need to create a new React project using the [Create React App CLI](https://github.com/facebook/create-react-app).\n\n```bash\n$ npx create-react-app my-amplify-app\n```\n\nNow change into the new app directory \u0026 install the AWS Amplify, AWS Amplify React, \u0026 uuid libraries:\n\n```bash\n$ cd my-amplify-app\n$ npm install --save aws-amplify aws-amplify-react uuid\n# or\n$ yarn add aws-amplify aws-amplify-react uuid\n```\n\n## Installing the CLI \u0026 Initializing a new AWS Amplify Project\n\n### Installing the CLI\n\nNext, we'll install the AWS Amplify CLI:\n\n```bash\n$ npm install -g @aws-amplify/cli\n```\n\nNow we need to configure the CLI with our credentials:\n\n```sh\n$ amplify configure\n```\n\n\u003e If you'd like to see a video walkthrough of this configuration process, click [here](https://www.youtube.com/watch?v=fWbM5DLh25U).\n\nHere we'll walk through the `amplify configure` setup. Once you've signed in to the AWS console, continue:\n- Specify the AWS Region: __us-east-1 || us-west-2 || eu-central-1__\n- Specify the username of the new IAM user: __amplify-workshop-user__\n\u003e In the AWS Console, click __Next: Permissions__, __Next: Tags__, __Next: Review__, \u0026 __Create User__ to create the new IAM user. Then, return to the command line \u0026 press Enter.\n- Enter the access key of the newly created user:   \n? accessKeyId: __(\u003cYOUR_ACCESS_KEY_ID\u003e)__   \n? secretAccessKey:  __(\u003cYOUR_SECRET_ACCESS_KEY\u003e)__\n- Profile Name: __amplify-workshop-user__\n\n### Initializing A New Project\n\n```bash\n$ amplify init\n```\n\n- Enter a name for the project: __amplifyreactapp__\n- Enter a name for the environment: __dev__\n- Choose your default editor: __Visual Studio Code (or your default editor)__   \n- Please choose the type of app that you're building __javascript__   \n- What javascript framework are you using __react__   \n- Source Directory Path: __src__   \n- Distribution Directory Path: __build__   \n- Build Command: __npm run-script build__   \n- Start Command: __npm run-script start__   \n- Do you want to use an AWS profile? __Y__\n- Please choose the profile you want to use: __amplify-workshop-user__\n\nNow, the AWS Amplify CLI has iniatilized a new project \u0026 you will see a new folder: __amplify__ \u0026 a new file called `aws-exports.js` in the __src__ directory. These files hold your project configuration.\n\nTo view the status of the amplify project at any time, you can run the Amplify `status` command:\n\n```sh\n$ amplify status\n```\n\n### Configuring the React applicaion\n\nNow, our resources are created \u0026 we can start using them!\n\nThe 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.\n\nTo configure the app, open __src/index.js__ and add the following code below the last import:\n\n```js\nimport Amplify from 'aws-amplify'\nimport config from './aws-exports'\nAmplify.configure(config)\n```\n\nNow, our app is ready to start using our AWS services.\n\n## Adding a GraphQL API\n\nTo add a GraphQL API, we can use the following command:\n\n```sh\n$ amplify add api\n\n? Please select from one of the above mentioned services: GraphQL\n? Provide API name: ConferenceAPI\n? Choose an authorization type for the API: API key\n? Enter a description for the API key: \u003csome description\u003e\n? After how many days from now the API key should expire (1-365): 365\n? Do you want to configure advanced settings for the GraphQL API: No\n? Do you have an annotated GraphQL schema? N \n? Do you want a guided schema creation? Y\n? What best describes your project: Single object with fields\n? Do you want to edit the schema now? (Y/n) Y\n```\n\n\u003e When prompted, update the schema to the following:   \n\n```graphql\n# amplify/backend/api/ConferenceAPI/schema.graphql\n\ntype Talk @model {\n  id: ID!\n  clientId: ID\n  name: String!\n  description: String!\n  speakerName: String!\n  speakerBio: String!\n}\n```\n\n## Local mocking and testing\n\nTo mock and test the API locally, you can run the `mock` command:\n\n```sh\n$ amplify mock api\n\n? Choose the code generation language target: javascript\n? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js\n? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Y\n? Enter maximum statement depth [increase from default if your schema is deeply nested]: 2\n```\n\nThis should start an AppSync Mock endpoint:\n\n```sh\nAppSync Mock endpoint is running at http://10.219.99.136:20002\n```\n\nOpen the endpoint in the browser to use the GraphiQL Editor.\n\nFrom here, we can now test the API.\n\n### Performing mutations from within the local testing environment\n\nExecute the following mutation to create a new talk in the API:\n\n```graphql\nmutation createTalk {\n  createTalk(input: {\n    name: \"Full Stack React\"\n    description: \"Using React to build Full Stack Apps with GraphQL\"\n    speakerName: \"Jennifer\"\n    speakerBio: \"Software Engineer\"\n  }) {\n    id name description speakerName speakerBio\n  }\n}\n```\n\nNow, let's query for the talks:\n\n```graphql\nquery listTalks {\n  listTalks {\n    items {\n      id\n      name\n      description\n      speakerName\n      speakerBio\n    }\n  }\n}\n```\n\nWe can even add search / filter capabilities when querying:\n\n```graphql\nquery listTalksWithFilter {\n  listTalks(filter: {\n    description: {\n      contains: \"React\"\n    }\n  }) {\n    items {\n      id\n      name\n      description\n      speakerName\n      speakerBio\n    }\n  }\n}\n```\n\n### Interacting with the GraphQL API from our client application - Querying for data\n\nNow that the GraphQL API server is running we can begin interacting with it!\n\nThe first thing we'll do is perform a query to fetch data from our API.\n\nTo do so, we need to define the query, execute the query, store the data in our state, then list the items in our UI.\n\n#### src/App.js\n\n```js\n// src/App.js\nimport React from 'react';\n\n// imports from Amplify library\nimport { API, graphqlOperation } from 'aws-amplify'\n\n// import query definition\nimport { listTalks as ListTalks } from './graphql/queries'\n\nclass App extends React.Component {\n  // define some state to hold the data returned from the API\n  state = {\n    talks: []\n  }\n\n  // execute the query in componentDidMount\n  async componentDidMount() {\n    try {\n      const talkData = await API.graphql(graphqlOperation(ListTalks))\n      console.log('talkData:', talkData)\n      this.setState({\n        talks: talkData.data.listTalks.items\n      })\n    } catch (err) {\n      console.log('error fetching talks...', err)\n    }\n  }\n  render() {\n    return (\n      \u003c\u003e\n        {\n          this.state.talks.map((talk, index) =\u003e (\n            \u003cdiv key={index}\u003e\n              \u003ch3\u003e{talk.speakerName}\u003c/h3\u003e\n              \u003ch5\u003e{talk.name}\u003c/h5\u003e\n              \u003cp\u003e{talk.description}\u003c/p\u003e\n            \u003c/div\u003e\n          ))\n        }\n      \u003c/\u003e\n    )\n  }\n}\n\nexport default App\n```\n\nIn the above code we are using `API.graphql` to call the GraphQL API, and then taking the result from that API call and storing the data in our state. This should be the list of talks you created via the GraphiQL editor.\n\n#### Feel free to add some styling here to your list if you'd like 😀\n\nNext, test the app locally:\n\n```sh\n$ npm start\n```\n\n## Performing mutations\n\n Now, let's look at how we can create mutations.\n\n To do so, we'll refactor our initial state in order to also hold our form fields and add an event handler.\n\n We'll also be using the `API` class from amplify again, but now will be passing a second argument to `graphqlOperation` in order to pass in variables: `API.graphql(graphqlOperation(CreateTalk, { input: talk }))`.\n\n We also have state to work with the form inputs, for `name`, `description`, `speakerName`, and `speakerBio`.\n\n```js\n// src/App.js\nimport React from 'react';\n\nimport { API, graphqlOperation } from 'aws-amplify'\n// import uuid to create a unique client ID\nimport uuid from 'uuid/v4'\n\nimport { listTalks as ListTalks } from './graphql/queries'\n// import the mutation\nimport { createTalk as CreateTalk } from './graphql/mutations'\n\nconst CLIENT_ID = uuid()\n\nclass App extends React.Component {\n  // define some state to hold the data returned from the API\n  state = {\n    name: '', description: '', speakerName: '', speakerBio: '', talks: []\n  }\n\n  // execute the query in componentDidMount\n  async componentDidMount() {\n    try {\n      const talkData = await API.graphql(graphqlOperation(ListTalks))\n      console.log('talkData:', talkData)\n      this.setState({\n        talks: talkData.data.listTalks.items\n      })\n    } catch (err) {\n      console.log('error fetching talks...', err)\n    }\n  }\n  createTalk = async() =\u003e {\n    const { name, description, speakerBio, speakerName } = this.state\n    if (name === '' || description === '' || speakerBio === '' || speakerName === '') return\n\n    const talk = { name, description, speakerBio, speakerName, clientId: CLIENT_ID }\n    const talks = [...this.state.talks, talk]\n    this.setState({\n      talks, name: '', description: '', speakerName: '', speakerBio: ''\n    })\n\n    try {\n      await API.graphql(graphqlOperation(CreateTalk, { input: talk }))\n      console.log('item created!')\n    } catch (err) {\n      console.log('error creating talk...', err)\n    }\n  }\n  onChange = (event) =\u003e {\n    this.setState({\n      [event.target.name]: event.target.value\n    })\n  }\n  render() {\n    return (\n      \u003c\u003e\n        \u003cinput\n          name='name'\n          onChange={this.onChange}\n          value={this.state.name}\n          placeholder='name'\n        /\u003e\n        \u003cinput\n          name='description'\n          onChange={this.onChange}\n          value={this.state.description}\n          placeholder='description'\n        /\u003e\n        \u003cinput\n          name='speakerName'\n          onChange={this.onChange}\n          value={this.state.speakerName}\n          placeholder='speakerName'\n        /\u003e\n        \u003cinput\n          name='speakerBio'\n          onChange={this.onChange}\n          value={this.state.speakerBio}\n          placeholder='speakerBio'\n        /\u003e\n        \u003cbutton onClick={this.createTalk}\u003eCreate Talk\u003c/button\u003e\n        {\n          this.state.talks.map((talk, index) =\u003e (\n            \u003cdiv key={index}\u003e\n              \u003ch3\u003e{talk.speakerName}\u003c/h3\u003e\n              \u003ch5\u003e{talk.name}\u003c/h5\u003e\n              \u003cp\u003e{talk.description}\u003c/p\u003e\n            \u003c/div\u003e\n          ))\n        }\n      \u003c/\u003e\n    )\n  }\n}\n\nexport default App\n```\n\n## Adding Authentication\n\nNext, let's update the app to add authentication.\n\nTo add authentication, we can use the following command:\n\n```sh\n$ amplify add auth\n\n? Do you want to use default authentication and security configuration? Default configuration \n? How do you want users to be able to sign in when using your Cognito User Pool? Username\n? Do you want to configure advanced settings? No, I am done.   \n```\n\n### Using the withAuthenticator component\n\nTo add authentication in the React app, we'll go into __src/App.js__ and first import the `withAuthenticator` HOC (Higher Order Component) from `aws-amplify-react`:\n\n```js\n// src/App.js, import the new component\nimport { withAuthenticator } from 'aws-amplify-react'\n```\n\nNext, we'll wrap our default export (the App component) with the `withAuthenticator` HOC:\n\n```js\n// src/App.js, change the default export to this:\nexport default withAuthenticator(App, { includeGreetings: true })\n```\n\nTo deploy the authentication service and mock and test the app locally, you can run the `mock` command:\n\n```sh\n$ amplify mock\n\n? Are you sure you want to continue? Yes\n```\n\nNext, to test it out in the browser:\n\n```sh\nnpm start\n```\n\nNow, 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 \u0026 sign in.\n\n\n### Accessing User Data\n\nWe can access the user's info now that they are signed in by calling `Auth.currentAuthenticatedUser()` in `componentDidMount`.\n\n```js\nimport {API, graphqlOperation, /* new 👉 */ Auth} from 'aws-amplify'\n\nasync componentDidMount() {\n  // add this code to componentDidMount\n  const user = await Auth.currentAuthenticatedUser()\n  console.log('user:', user)\n  console.log('user info:', user.signInUserSession.idToken.payload)\n}\n```\n\n## Adding Authorization to the GraphQL API\n\nNext we need to update the AppSync API to now use the newly created Cognito Authentication service as the authentication type.\n\nTo do so, we'll reconfigure the API:\n\n```sh\n$ amplify update api\n\n? Please select from one of the below mentioned services: GraphQL   \n? Choose the default authorization type for the API: Amazon Cognito User Pool\n? Do you want to configure advanced settings for the GraphQL API: No, I am done\n```\n\nNext, we'll test out the API with authentication enabled:\n\n```sh\n$ amplify mock\n```\nNow, we can only access the API with a logged in user.\n\nYou'll notice an __auth__ button in the GraphiQL explorer that will allow you to update the simulated user and their groups.\n\n### Fine Grained access control - Using the @auth directive\n\n####  GraphQL Type level authorization with the @auth directive\n\nFor authorization rules, we can start using the `@auth` directive.\n\nWhat if you'd like to have a new `Comment` type that could only be updated or deleted by the creator of the `Comment` but can be read by anyone?\n\nWe could add the following type to our GraphQL schema:\n\n```graphql\n# amplify/backend/api/ConferenceAPI/schema.graphql\n\ntype Comment @model @auth(rules: [\n  { allow: owner, ownerField: \"createdBy\", operations: [create, update, delete]},\n  { allow: private, operations: [read] }\n  ]) {\n  id: ID!\n  message: String\n  createdBy: String\n}\n```\n\n__allow: owner__ - This allows us to set owner authorization rules.   \n__allow: private__ - This allows us to set private authorization rules.   \n\nThis would allow us to create comments that only the creator of the Comment could delete, but anyone could read.\n\nCreating a comment:\n\n```graphql\nmutation createComment {\n  createComment(input:{\n    message: \"Cool talk\"\n  }) {\n    id\n    message\n    createdBy\n  }\n}\n```\n\nListing comments:\n\n```graphql\nquery listComments {\n  listComments {\n    items {\n      id\n      message\n      createdBy\n    }\n  }\n}\n```\n\nUpdating a comment:\n\n```graphql\nmutation updateComment {\n  updateComment(input: {\n    id: \"59d202f8-bfc8-4629-b5c2-bdb8f121444a\"\n  }) {\n    id \n    message\n    createdBy\n  }\n}\n```\n\nIf you try to update a comment from someone else, you will get an unauthorized error.\n\n### Relationships\n\nWhat if we wanted to create a relationship between the Comment and the Talk? That's pretty easy. We can use the `@connection` directive:\n\n```graphql\n# amplify/backend/api/ConferenceAPI/schema.graphql\n\ntype Talk @model {\n  id: ID!\n  clientId: ID\n  name: String!\n  description: String!\n  speakerName: String!\n  speakerBio: String!\n  comments: [Comment] @connection(name: \"TalkComments\")\n}\n\ntype Comment @model @auth(rules: [\n  { allow: owner, ownerField: \"createdBy\", operations: [create, update, delete]},\n  { allow: private, operations: [read] }\n  ]) {\n  id: ID!\n  message: String\n  createdBy: String\n  talk: Talk @connection(name: \"TalkComments\")\n}\n```\n\nBecause we're updating the way our database is configured by adding relationships which requires a global secondary index, we need to delete the old local database:\n\n```sh\n$ rm -r amplify/mock-data\n```\n\nNow, restart the server:\n\n```sh\n$ amplify mock\n```\n\nNow, we can create relationships between talks and comments. Let's test this out with the following operations:\n\n```graphql\nmutation createTalk {\n  createTalk(input: {\n    id: \"test-id-talk-1\"\n    name: \"Talk 1\"\n    description: \"Cool talk\"\n    speakerBio: \"Cool gal\"\n    speakerName: \"Jennifer\"\n  }) {\n    id\n    name\n    description\n  }\n}\n\nmutation createComment {\n  createComment(input: {\n    commentTalkId: \"test-id-talk-1\"\n    message: \"Great talk\"\n  }) {\n    id message\n  }\n}\n\nquery listTalks {\n  listTalks {\n    items {\n      id\n      name\n      description\n      comments {\n        items {\n          message\n          createdBy\n        }\n      }\n    }\n  }\n}\n```\n\nIf you'd like to read more about the `@auth` directive, check out the documentation [here](https://aws-amplify.github.io/docs/cli/graphql#auth).\n\n### Groups\n\nThe last problem we are facing is that *anyone* signed in can create a new talk. Let's add authorization that only allows users that are in an __Admin__ group to create and update talks.\n\n```graphql\n# amplify/backend/api/ConferenceAPI/schema.graphql\n\ntype Talk @model @auth(rules: [\n  { allow: groups, groups: [\"Admin\"] },\n  { allow: private, operations: [read] }\n  ]) {\n  id: ID!\n  clientId: ID\n  name: String!\n  description: String!\n  speakerName: String!\n  speakerBio: String!\n  comments: [Comment] @connection(name: \"TalkComments\")\n}\n\ntype Comment @model @auth(rules: [\n  { allow: owner, ownerField: \"createdBy\", operations: [create, update, delete]},\n  { allow: private, operations: [read] }\n  ]) {\n  id: ID!\n  message: String\n  createdBy: String\n  talk: Talk @connection(name: \"TalkComments\")\n}\n```\n\nRun the server:\n\n```sh\n$ amplify mock\n```\n\nClick on the __auth__ button and add __Admin__ the user's groups.\n\nNow, you'll notice that only users in the __Admin__ group can create, update, or delete a talk, but anyone can read it.\n\n## Lambda GraphQL Resolvers\n\nNext, let's have a look at how to deploy a serverless function and use it as a GraphQL resolver.\n\nThe use case we will work with is fetching data from another HTTP API and returning the response via GraphQL. To do this, we'll use a serverless function.\n\nThe API we will be working with is the CoinLore API that will allow us to query for cryptocurrency data.\n\nTo get started, we'll create the new function:\n\n```sh\n$ amplify add function\n\n? Provide a friendly name for your resource to be used as a label for this category in the project: currencyfunction\n? Provide the AWS Lambda function name: currencyfunction\n? Choose the function template that you want to use: Hello world function\n? Do you want to access other resources created in this project from your Lambda function? N\n? Do you want to edit the local lambda function now? Y\n```\n\nUpdate the function with the following code:\n\n```javascript\n// amplify/backend/function/currencyfunction/src/index.js\nconst axios = require('axios')\n\nexports.handler = function (event, _, callback) {\n  let apiUrl = `https://api.coinlore.com/api/tickers/?start=1\u0026limit=10`\n\n  if (event.arguments) { \n    const { start = 0, limit = 10 } = event.arguments\n    apiUrl = `https://api.coinlore.com/api/tickers/?start=${start}\u0026limit=${limit}`\n  }\n\n  axios.get(apiUrl)\n    .then(response =\u003e callback(null, response.data.data))\n    .catch(err =\u003e callback(err))\n}\n```\n\nIn the above function we've used the [axios](https://github.com/axios/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:\n\n__amplify/backend/function/currencyfunction/src/package.json__\n\n```json\n\"dependencies\": {\n  // ...\n  \"axios\": \"^0.19.0\",\n},\n```\nNext, we'll update the GraphQL schema to add a new type and query. In amplify/backend/api/ConferenceAPI/schema.graphql, update the schema with the following new types:\n\n```graphql\ntype Coin {\n  id: String!\n  name: String!\n  symbol: String!\n  price_usd: String!\n}\n\ntype Query {\n  getCoins(limit: Int start: Int): [Coin] @function(name: \"currencyfunction-${env}\")\n}\n```\n\nNow the schema has been updated and the Lambda function has been created. To test it out, you can run the mock command:\n\n```sh\n$ amplify mock\n```\n\nIn the query editor, run the following queries:\n\n```graphql\n# basic request\nquery listCoins {\n  getCoins {\n    price_usd\n    name\n    id\n    symbol\n  }\n}\n\n# request with arguments\nquery listCoinsWithArgs {\n  getCoins(limit:3 start: 10) {\n    price_usd\n    name\n    id\n    symbol\n  }\n}\n```\n\nThis query should return an array of cryptocurrency information.\n\n## Deploying the Services\n\nNext, let's deploy the AppSync GraphQL API and the Lambda function:\n\n```bash\n$ amplify push\n\n? Do you want to generate code for your newly created GraphQL API? Y\n? Choose the code generation language target: javascript\n? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js\n? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions? Y\n? Enter maximum statement depth [increase from default if your schema is deeply nested] 2\n```\n\nTo view the new AWS AppSync API at any time after its creation, run the following command:\n\n```sh\n$ amplify console api\n```\n\nTo view the Cognito User Pool at any time after its creation, run the following command:\n\n```sh\n$ amplify console auth\n```\n\nTo test an authenticated 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.\n\n## Hosting via the Amplify Console\n\nThe Amplify Console is a hosting service with continuous integration and continuous deployment.\n\nThe 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 \u0026 initialize git in our local project:\n\n```sh\n$ git init\n\n$ git remote add origin git@github.com:username/project-name.git\n\n$ git add .\n\n$ git commit -m 'initial commit'\n\n$ git push origin master\n```\n\nNext we'll visit the Amplify Console in our AWS account at [https://us-east-1.console.aws.amazon.com/amplify/home](https://us-east-1.console.aws.amazon.com/amplify/home).\n\nHere, we'll click on the app that we deployed earlier.\n\nNext, under \"Frontend environments\", authorize Github as the repository service.\n\nNext, we'll choose the new repository \u0026 branch for the project we just created \u0026 click __Next__.\n\nIn the next screen, we'll create a new role \u0026 use this role to allow the Amplify Console to deploy these resources \u0026 click __Next__.\n\nFinally, we can click __Save and Deploy__ to deploy our application!\n\nNow, we can push updates to Master to update our application.\n\n## Amplify DataStore\n\nTo implement a GraphQL API with Amplify DataStore, check out the tutorial [here](https://github.com/dabit3/amplify-datastore-example)\n\n## Removing Services\n\nIf at any time, or at the end of this workshop, you would like to delete a service from your project \u0026 your account, you can do this by running the `amplify remove` command:\n\n```sh\n$ amplify remove auth\n\n$ amplify push\n```\n\nIf you are unsure of what services you have enabled at any time, you can run the `amplify status` command:\n\n```sh\n$ amplify status\n```\n\n`amplify status` will give you the list of resources that are currently enabled in your app.\n\nIf you'd like to delete the entire project, you can run the `delete` command:\n\n```sh\n$ amplify delete\n```\n\n\u003c!-- ### GraphQL Subscriptions\n\nNext, let's see how we can create a subscription to subscribe to changes of data in our API.\n\nTo do so, we need to define the subscription, listen for the real-time data coming in from the subscription, \u0026 update the state whenever a new piece of data comes in.\n\n```js\n// import the subscription\nimport { onCreateTalk as OnCreateTalk } from './graphql/subscriptions'\n\n// define the subscription in the class\nsubscription = {}\n\n// subscribe in componentDidMount\ncomponentDidMount() {\n  this.subscription = API.graphql(\n    graphqlOperation(OnCreateTalk)\n  ).subscribe({\n      next: (eventData) =\u003e {\n        console.log('eventData', eventData)\n        const talk = eventData.value.data.onCreateTalk\n        if (talk.clientId === CLIENT_ID) return\n        const talks = [ ...this.state.talks, talk ]\n        this.setState({ talks })\n      }\n  })\n}\n\n// unsubscribe in componentWillUnmount\ncomponentWillUnmount() {\n  this.subscription.unsubscribe()\n}\n``` --\u003e","funding_links":[],"categories":["Workshops"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdabit3%2Faws-appsync-react-workshop","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdabit3%2Faws-appsync-react-workshop","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdabit3%2Faws-appsync-react-workshop/lists"}