Using AWS as a Back End: Authentication & API

Learn how to use Amazon Web Services (AWS) to build a back end for your iOS apps with AWS Amplify and Cognito, using GraphQL. By Tom Elliott.

4.3 (3) · 1 Review

Download materials
Save for later
Share
You are currently viewing page 3 of 4 of this article. Click here to view the first page.

GraphQL, AppSync and DynamoDB

Providing login capability in your app is a good start. But most products also need a way for users to modify and save data. For many modern apps, this data needs to be accessible to other users. A common solution to this problem is to persist the data in a database stored on a server somewhere in the cloud.

AWS provides many different database services, each with its own benefits and trade-offs. In this tutorial, you’ll use the document database DynamoDB. With DynamoDB, you don’t have to define a schema up front. This feature lends itself to quick prototyping or iterating on new ideas for your app.

Many mobile apps use a common architectural pattern in which the business and security logic resides in a back-end server. The app communicates with the server via a network API like GraphQL or REST. The server saves, retrieves or updates records in a database.

AppSync is an AWS service that generates both the database and the back end automatically, using your GraphQL schema. You define your model objects in the GraphQL schema, and AppSync generates the code for the back end. It then deploys the services needed to run your back end. And it creates the DynamoDB tables required to save your data.

Adding a GraphQL API

Back in Xcode, open Podfile and add the following dependency:

pod 'AmplifyPlugins/AWSAPIPlugin'

AWSAPIPlugin adds support to the Amplify Library for AppSync. Update your workspace by running the following from the command line:

pod install --repo-update

The first model object you’re going to add is a User object. Normally, Cognito handles user data. But Cognito’s data is private to the individual. And, in the Isolation Nation app, users must be able to see data about each other, such as their username. So this app needs a User Model as well as the Cognito data.

Defining Your Schema

In Xcode, open schema.graphql in the AmplifyConfig group. Replace the contents with the following:

# 1
type User
  # 4
  @model
{
  # 2
  id: ID!
  username: String!
  # 3
  sub: String!
  postcode: String
  createdAt: AWSDateTime!
}

Here’s what you’re doing:

  1. You declare a User type.
  2. You define various fields for the user type as code: Type tuples. For example, the id field is of type ID, and the postcode field is of type String. The ! operator signifies that a type is required.
  3. The sub field will contain the sub record from Cognito. This is the unique identifier for the user.
  4. You annotate the user type with the @model directive.

If you’re familiar with GraphQL, most of this will look pretty straightforward. However, there are a few bits unique to AppSync.

AppSync uses directives to provide a declarative API that allows you to specify how you want AppSync to configure each type or field. In this example, you specify that your user type is a model. This indicates to AppSync that it should create a DynamoDB table for this type.

Note: AppSync makes liberal use of GraphQL Directives. You’ll find a full list of directives here.

When you added Amplify Tools as a dependency in your project earlier, Amplify created an API on your behalf. However, this was before you added authentication to the project. Your API doesn’t know anything about the Cognito User Pool you just created. Before you continue, you need to fix that.

Generating the Database

In your terminal, run the following command:

amplify api update

When prompted, select GraphQLUpdate auth settingsAmazon Cognito User Pool, and then N.

Next, open amplifytools.xcconfig. Override the options by adding the code:

push=true
modelgen=true
profile=default
envName=dev

Here, you’re instructing the Amplify Tools script to take these actions:

  • Push changes to the cloud when it runs.
  • Generate models in Swift for your @model types.
  • Use your default AWS profile and the dev environment you created earlier.

Build your project in Xcode. If you open the Report navigator, you’ll see that the Amplify Tools script is now generating Swift models on your behalf.

Generating models

This build will take a long time! This is because the script is also running amplify push to generate all the necessary resources in the cloud.

Generating resources in AWS

When the build is complete, open the Project navigator. Confirm that a new group has been added to your project, and that it contains generated model files for your User model.

Swift generated models

In your browser, go back to the Amplify Console and reload the page. Select Backend environments and then click the API link.

Your api in the amplify console

On the API page, note the addition of a UserTable under the Data sources section. Click the View in AppSync button.

The User Table in the Amplify Console

On the AppSync page, open the Run a query accordion and click the Run a query button.

Running a Query from the AWS AppSync Console

This opens a GraphQL Playground that allows you to run live queries and mutations against your GraphQL API. Click the Login with User Pools button and sign in, using the Client ID you copied earlier and the credentials you created for your user. Press Login.

Login to your GraphQL API

Writing Data

Next, you’ll create a User model. First, if the Explorer pane is open, close it by clicking the X. Now, in the leftmost pane, add the following code, using the name of your user for username and the sub you copied earlier for both the id and sub fields:

mutation CreateUserMutation {
  createUser(input:{
    id: "389b0b66-f0e3-4907-9b4e-01ac4146bb0b"
    username: "Lizzie",
    sub: "389b0b66-f0e3-4907-9b4e-01ac4146bb0b",
  }) {
    id
    username
    sub
    createdAt
  }
}

Unfortunately, you can’t add comments to the GraphQL code. The following line numbers refer to those in the screenshot below.

  • On line 1, you define a named mutation called CreateUserMutation.
  • In lines 2–5, you run the createUser mutation generated by AppSync from your GraphQL schema. The mutation takes a single parameter called input. This parameter contains the username and sub for the user you want to create.
  • Lines 6–9 define the response to the mutation. You specify that id, username,
    sub and createdAt should be returned in the response. These are all fields of the created user.

Now press the orange Play button to run the mutation and create your user.

Creating a user in the GraphQL playground

Your mutation is sent to your AppSync GraphQL server, and the response appears in the middle column.

Next, select Data Sources in the left-hand menu. Then select the DynamoDB Resource for your UserTable.

Your browser will open a new tab. You’ll see your new DynamoDB database table. Select the Items tab.

The Items tab displays a single record. This is the user you just created. Now, click the record ID link to open the database record for your user.

Viewing a User record

Congratulations! You’ve just successfully created your first database record in DynamoDB. :]