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.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Using AWS as a Back End: Authentication & API
35 mins
- Getting Started
- Introduction to the App
- Setting Up Your Environment
- AWS Amplify
- Installing and Configuring Amplify
- Adding Amplify to Your App
- Configuring AWS Cognito
- Adding Authentication With Amazon Cognito
- Completing the Authentication Service
- GraphQL, AppSync and DynamoDB
- Adding a GraphQL API
- Defining Your Schema
- Generating the Database
- Writing Data
- Reading and Writing AppSync Data From Swift
- Reading Data From AppSync
- Creating Data in DynamoDB
- Where to Go From Here?
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:
- You declare a
User
type. - You define various fields for the user type as
code: Type
tuples. For example, theid
field is of typeID
, and thepostcode
field is of typeString
. The!
operator signifies that a type is required. - The
sub
field will contain thesub
record from Cognito. This is the unique identifier for the user. - 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.
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 GraphQL ▸ Update auth settings ▸ Amazon 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.
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.
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.
In your browser, go back to the Amplify Console and reload the page. Select Backend environments and then click the API link.
On the API page, note the addition of a UserTable under the Data sources section. Click the View in AppSync button.
On the AppSync page, open the Run a query accordion and click the Run a query button.
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.
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 calledinput
. 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
andcreatedAt
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.
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.
Congratulations! You’ve just successfully created your first database record in DynamoDB. :]