AWS Mobile Hub Developer Guide
Developer Guide

Access Your Database

Important

The following content applies if you are already using the AWS Mobile CLI to configure your backend. If you are building a new mobile or web app, or you're adding cloud capabilities to your existing app, use the new AWS Amplify CLI instead. With the new Amplify CLI, you can use all of the features described in Announcing the AWS Amplify CLI toolchain, including AWS CloudFormation functionality that provides additional workflows.

Set Up Your Backend

The AWS Mobile CLI and Amplify library make it easy to perform create, read, update, and delete ("CRUD") actions against data stored in the cloud through simple API calls in your JavaScript app.

BEFORE YOU BEGIN

The steps on this page assume you have already completed the steps on Get Started.

To create a database

  1. Enable the NoSQL database feature and configure your table.

    In the root folder of your app, run:

    awsmobile database enable --prompt
  2. Choose Open to make the data in this table viewable by all users of your application.

    ? Should the data of this table be open or restricted by user? ❯ Open Restricted
  3. For this example type in todos as your Table name.

    ? Table name: todos

Add columns and queries

You are creating a table in a NoSQL database and adding an initial set of columns, each of which has a name and a data type. NoSQL lets you add a column any time you store data that contains a new column. NoSQL tables must have one column defined as the Primary Key, which is a unique identifier for each row.

  1. For this example, follow the prompts to add three columns: team (string), todoId (number), and text (string).

    ? What would you like to name this column: team ? Choose the data type: string
  2. When prompted to ? Add another column, type Y and then choose enter. Repeat the steps to create todoId and text columns.

  3. Select team as the primary key.

    ? Select primary key ❯ team todoId text
  4. Choose (todoId) as the sort key and then no to adding any more indexes, to keep the example simple.

    Sort Keys and Indexes

    To optimize performance, you can define a column as a Sort Key. Choose a column to be a Sort Key if it will be frequently used in combination with the Primary key to query your table. You can also create Secondary Indexes to make additional columns sort keys.

    ? Select sort key ❯ todoId text (No Sort Key) ? Add index (Y/n): n Table todos saved.

    The todos table is now created.

Use a cloud API to do CRUD operations

To access your NoSQL database, you will create an API that can be called from your app to perform CRUD operations.

Why an API?

Using an API to access your database provides a simple coding interface on the front end and robust flexibility on the backend. Behind the scenes, a call to an Amazon API Gateway API end point in the cloud is handled by a serverless Lambda function.

To create a CRUD API

  1. Enable and configure the Cloud Logic feature**

    awsmobile cloud-api enable --prompt
  2. Choose Create CRUD API for an existing Amazon DynamoDB table API for an existing Amazon DynamoDB table" and then choose enter.

    ? Select from one of the choices below. (Use arrow keys) Create a new API ❯ Create CRUD API for an existing Amazon DynamoDB table
  3. Select the todos table created in the previous steps, and choose enter.

    ? Select Amazon DynamoDB table to connect to a CRUD API ❯ todos
  4. Push your configuration to the cloud. Without this step, the configuration for your database and API is now in place only on your local machine.

    awsmobile push

    The required DynamoDB tables, API Gateway endpoints, and Lambda functions will now be created.

Create your first Todo

The AWS Mobile CLI enables you to test your API from the command line.

Run the following command to create your first todo.

awsmobile cloud-api invoke todosCRUD POST /todos '{"body": {"team": "React", "todoId": 1, "text": "Learn more Amplify"}}'

Connect to Your Backend

The examples in this section show how you would integrate AWS Amplify library calls using React (see the AWS Amplify documentation to use other flavors of Javascript).

The following component is a simple Todo list that you might add to a create-react-app project. The Todos component currently adds and displays todos to and from an in memory array.

// To Do app example import React from 'react'; class Todos extends React.Component { state = { team: "React", todos: [] }; render() { let todoItems = this.state.todos.map(({todoId, text}) => { return <li key={todoId}>{text}</li>; }); return ( <div style={styles}> <h1>{this.state.team} Todos</h1> <ul> {todoItems} </ul> <form> <input ref="newTodo" type="text" placeholder="What do you want to do?" /> <input type="submit" value="Save" /> </form> </div> ); } } let styles = { margin: "0 auto", width: "25%" }; export default Todos;

Displaying todos from the cloud

The API module from AWS Amplify allows you connect to DynamoDB through API Gateway endpoints.

To retrieve and display items in a database

  1. Import the API module from aws-amplify at the top of the Todos component file.

    import { API } from 'aws-amplify';
  2. Add the following componentDidMount to the Todos component to fetch all of the todos.

    async componentDidMount() { let todos = await API.get('todosCRUD', `/todos/${this.state.team}`); this.setState({ todos }); }

When the Todos component mounts it will fetch all of the todos stored in your database and display them.

Saving todos to the cloud

The following fragment shows the saveTodo function for the Todo app.

async saveTodo(event) { event.preventDefault(); const { team, todos } = this.state; const todoId = todos.length + 1; const text = this.refs.newTodo.value; const newTodo = {team, todoId, text}; await API.post('todosCRUD', '/todos', { body: newTodo }); todos.push(newTodo); this.refs.newTodo.value = ''; this.setState({ todos, team }); }

Update the form element in the component's render function to invoke the saveTodo function when the form is submitted.

<form onSubmit={this.saveTodo.bind(this)}>

Your entire component should look like the following:

// To Do app example import React from 'react'; import { API } from 'aws-amplify'; class Todos extends React.Component { state = { team: "React", todos: [] }; async componentDidMount() { const todos = await API.get('todosCRUD', `/todos/${this.state.team}`) this.setState({ todos }); } async saveTodo(event) { event.preventDefault(); const { team, todos } = this.state; const todoId = todos.length + 1; const text = this.refs.newTodo.value; const newTodo = {team, todoId, text}; await API.post('todosCRUD', '/todos', { body: newTodo }); todos.push(newTodo); this.refs.newTodo.value = ''; this.setState({ todos, team }); } render() { let todoItems = this.state.todos.map(({todoId, text}) => { return <li key={todoId}>{text}</li>; }); return ( <div style={styles}> <h1>{this.state.team} Todos</h1> <ul> {todoItems} </ul> <form onSubmit={this.saveTodo.bind(this)}> <input ref="newTodo" type="text" placeholder="What do you want to do?" /> <input type="submit" value="Save" /> </form> </div> ); } } let styles = { margin: "0 auto", width: "25%" } export default Todos;

Next Steps