In this article, we’ll showcase the new-ish built-in Data API feature for Aurora Severless MySQL Databases. Using this API, you can access Aurora Serverless with web services–based applications through a REST API with Amazon API Gateway + AWS Lambda, or a GraphQL API with AWS AppSync.

Let’s recap why you would want to use the Data API with Aurora Serverless Cluster…

With Data API enabled on an Aurora MySQL database, clients are no longer required to keep a persistent connection to the DB cluster and it Provides a secure HTTP endpoint and integration with AWS SDKs. You can use the endpoint to execute SQL statements in the same way as you go through the MySQL native protocol, but without managing connections. The Data API is sort of doing what Jeremy Daly and others have solved in this GitHub repo that works for serverless and serverful clusters.

In this article, we’ll be connecting an iOS app to a serverless MySQL database via a GraphQL API using AWS AppSync.

Note: This is a comprehensive blog that provides nearly every step from DB creation to client implementation. If this solution doesn’t work for you, please let me know and I’ll fix it.

In my previous article and video for getting started with Amazon Aurora Serverless Data API, I went over three ways to create an Aurora Serverless MySQL Database with Data API and four ways to connect into a serverless MySQL database. For this article, we’ll be using the Amazon RDS Console to create our database, enable Data API, and the Query Editor to define our tables and perform some basic crud operations.

Here’s what we’ll be building:

Amazon Aurora Serverless Cluster and MySQL Database with Data API enabled A new GraphQL API with AWS AppSync to interface with the above database An iOS Swift app to interact with our serverless MySQL database via the GraphQL API in “API_Key mode”.

Getting Started —Step 1

Create Cluster

The RDS Console is a quick way to deploy your resources and be done in just a few minutes following these instructions:

Create a new Aurora Serverless Cluster via RDS Console:

Launch the Amazon RDS Console. Select Create database. Select Easy Create. Select Engine type: Amazon Aurora. Select Edition: Amazon Aurora with MySQL 5.6 compatibility. Select DB instance size: Serverless Leave all defaults and choose Create database.

Screencast for creating an Aurora Serverless Cluster via the RDS Console

When creating a new Aurora Serverless MySQL database, the Data API should already be ENABLED. If not, or if you would like to verify, follow these steps below.

Verify Database has Data API ENABLED

We are going to verify the Data API for the newly created Aurora serverless database is enabled.

Launch the RDS Management Console Select Databases from the left panel. Select your database under DB identifier. Select the Modify button on the upper right. Data API under the Network & Security section should show a check indicating the Data API is ENABLED for this database. Select Continue. Select Apply immediately under Scheduling of modifications if changes were made. Select Modify cluster radio button.

Prepare Data

We’ll use the Query Editor in the RDS Console to create our database, tables, and insert a little data to get us started. The first time that you use the Query Editor, it’ll ask you for the Cluster credentials in the form of a master user and password. In response to providing those credentials, RDS will create a new AWS Secrets to store these creds and will retrieve these master user/pass whenever you return to connect to your database via the Query Editor.

Note: AWS Secrets Manager is a requirement to connect to your Data API enabled serverless cluster from the AWS CLI, SDK, AppSync, and other web-based applications. This a great way to keep the connection string from being passed into each sql statement.

Create Database & Tables

Launch Amazon RDS Management Console

Select Query Editor

In the Connect to Database window, select your cluster, provide your master user, master password, and database name (optional).

window, select your cluster, provide your master user, master password, and database name (optional). Select Connect to database.

In the query editor window, run the following commands:

Create a new database called AWSAlerts.

CREATE DATABASE AWSAlerts;

Create a new table called MyAWSService. I added the ‘My’ because of the name AWSService was conflicting somewhere as a reserved name.

USE AWSAlerts;

CREATE TABLE MyAWSService (

id MEDIUMINT NOT NULL PRIMARY KEY,

shortName varchar(50),

longName varchar(50),

description TEXT,

serviceRegionName varchar(50) NOT NULL,

feedUrl varchar(50),

imageUrl varchar(50)

);

What is AWSAlerts? This is a side project that I’m working on that monitors the AWS Service Health Dashboard and notifies subscribers of new, updated, or resolved dashboard events for all AWS services or networking events. The MyAWSService table will store the properties of each unique service and region along with their RSS feed URL, servie icon, and other details about that service.

Download the Demo iOS Project

$ git clone https://github.com/mobilequickie/iOS-RDS-Demo.git $ cd iOS-RDS-Demo/

Create GraphQL API

Now that we have a database, an AWSService table, and a base sample iOS app, let’s create a GraphQL API using the AWS Amplify CLI.

Amplify CLI — Installing the CLI

If you haven’t installed the AWS Amplify CLI before, run through these two commands below to install and configure the CLI before moving on. If you have the AWS CLI installed and configured with a profile, the Amplify CLI will utilize those credentials and therefore just install the CLI, the amplify configure is not necessary.

$ npm install -g @aws-amplify/cli

$ amplify configure

Amplify CLI — Init

Launch Mac Terminal in the root of the iOS project folder you just cloned earlier and cd to your Xcode project root folder:

$ cd iOS-RDS-Demo/

We’ll be working from the local project root folder so the Amplify CLI can update the iOS project when it provisions the backend resources. The CLI will create our API, grant permissions for the iOS app to invoke the API, and configuring our iOS client to connect into those backend resources via the AWS SDK for iOS.

Amplify CLI —Init

From your project root folder, run:

$ amplify init

Amplify CLI — Add API

$ amplify add api

? Please select from one of the below mentioned services GraphQL

? Provide API name: iosdemo

? Choose an authorization type for the API API key

? Do you have an annotated GraphQL schema? No

? Do you want a guided schema creation? Yes

? What best describes your project: Single object with fields (e.g., “Todo” with ID, name, description)

? Do you want to edit the schema now? Yes

Please edit the file in your editor: /Users/denhills/Desktop/iOS-RDS-Demo/amplify/backend/api/iosdemo/schema.graphql

Paste in the following definition as this is the bare minimum for creating a GraphQL schema. We don’t want to set up anything more as we’ll be using a plugin next to build out our schema based on the MySQL table column definitions.

schema {

query: Query

}

Save the schema and go back to the terminal and press enter to continue.

? Press enter to continue

Amplify CLI — Add MySQL Database as GraphQL DataSource

This is where we add our Aurora Serverless MySQL database ‘AWSAlerts’ as a datasource to our GraphQL API. Amplify CLI provides a plugin that will generate a GraphQL schema, resolvers, mutations, queries, and subscriptions based on your database table column definitions. Let’s run that plugin now.

$ amplify api add-graphql-datasource

? Provide the region in which your cluster is located: us-east-1

? Select the Aurora Serverless cluster that will be used as the data source for your API: my-serverless-cluster-rdsauroraserverlesscluster-SAMPLE

✔ Fetched Aurora Serverless cluster.

? Select the database to use as the datasource: AWSAlerts

Successfully added the Aurora Serverless datasource locally

Amplify CLI — Push

$ amplify push

? Do you want to generate code for your newly created GraphQL API Yes

? Enter the file name pattern of graphql queries, mutations and subscriptions graphql/**/*.graphql

? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes

? Enter maximum statement depth [increase from default if your schema is deeply nested] 2

? Enter the file name for the generated code API.swift

⠏ Updating resources in the cloud. This may take a few minutes...

Now that we have our API connected to our database, we can try out a few CRUD operations from the AWS AppSync Console to make sure everything is working properly before moving onto the iOS client.

1. Launch the AppSync Console. 2. Select the Query feature on the left. 3. Paste in the following GraphQL Mutation to create a new AWS Service in the MyAWSService table of the AWSAlerts database. Choose play button and you should see the list of fields and returned id.

mutation CreateAWSService {

createAWSService(createAWSServiceInput: {

id: 1

shortName: "EC2",

longName: "Amazon Elastic Compute Cloud",

serviceRegionName: "ec2-us-east-1",

feedUrl: "",

imageUrl: "ec2"

}) {

shortName

longName

serviceRegionName

feedUrl

imageUrl

}

}

4. Add a Query by pasting in the following just below the mutation. Choose play and select this query and you should see the id, longName, and shortName returned for at least one service your created in the previous mutation.

query ListAWSServices {

listAWSServices {

id

longName

shortName

}

}

Here’s what the testing of the mutation and query looks like in the AppSync Console

Now that we have the schema, mutations, queries, subscriptions, and resolvers connected to our serverless Aurora database as a datasource for our GraphQL API, we can now start using our mobile client with the generated API.swift code to interact with this structured data!

iOS Client

In your Xcode project folder, you should now have an awsconfiguration.json file that was autogenerated for you by the Amplify CLI as you added categories. In addition, the CLI codegen feature created an API.swift file that defines the GraphQL mutations, queries, and subscriptions for us to invoke these directly from the iOS app. To start, we’ll first need to install the AWS SDK for iOS.

iOS Client — Part 1

Add AWS SDK for iOS (Cocoapods)

To configure the app, we’ll use Cocoapods to install the AWS SDK for iOS and AWS AppSync Client dependencies. In the root project folder, run the following command to initialize Cocoapods.

pod init

This will create a new Podfile . Open up the Podfile in your favorite editor and add the following dependency for the AWSAppSync SDK:

target 'RDSDemo' do

use_frameworks! # Pods for ios-amplify-app

pod 'AWSAppSync', ' ~> 2.10.0'



end

Install the AppSync iOS SDK by running:

$ pod install --repo-update

iOS Client — Part 2

Integrate awsconfiguration.json and API.swift files into your Xcode project.

We need to configure our iOS Swift application to be aware of our new AWS Amplify project. We do this by referencing the auto-generated awsconfiguration.json and API.Swift files in the root of your Xcode project folder.

Launch Xcode using the .xcworkspace from now on as we are using Cocoapods.

$ open RDSDemo.xcworkspace/

In Xcode, right-click on the project folder and choose "Add Files to ..." and add awsconfiguration.json and the API.swift files to your project. When the Options dialog box that appears, do the following:

Clear the Copy items if needed checkbox.

Choose Create groups, and then choose Next.

Build the project (Command-B) to make sure we don’t have any compile errors.

iOS Client — Part 3

Implement the AWSAppSync Client. This is the basic client configuration when using “API_Key authorization”. This is NOT TYPICAL for an iOS app connecting to an AWS service. It’s just the easiest approach for domonstration purposes. Typically you would add auth via Amazon Cognito User Pools or other social identity provider, or even unauthenticated access via Amazon Cognito Identity Pool.

Add the following four numbered code snippets to your AWSServicesTableViewController.swift class:

iOS Client — Part 4

Add a GraphQL Mutation — Create a new AWS Service in the MyAWSService Table

Add the following mutation function to your AWSServicesTableViewController.swift class:

2. Add the call to createServiceMutation() in viewDidLoad()

createServiceMutation()

iOS Client — Part 5

Add a GraphQL Query — List all AWS Services in the MyAWSService Table

Add the following query function to your AWSServicesTableViewController.swift class: class:

2. Add the call to getServicesQuery() in viewDidLoad() and comment out the mutation

getServicesQuery()

3. Add awsServices class variable to the AWSServicesTableViewController

// class level variable

var awsServices: [ListAwsServicesQuery.Data.ListAwsService] = []

4. Comment out the hard-coded var awsServices = […] as we are now dynamically loading this variable from the query results.

iOS Client — Part 6

Build and run the app.

The starter iOS app you cloned earlier a select few service icons (as you can see below). The table view will display the entire list of AWS services you add to the MyAWSService table. The client is setup to display the cached list first and then fetch the latest from the server. You can launch the app, view the results, then go back to update the table via AppSync Console or the RDS Console, then launch the app again. You’ll see the app show the cached results immediately and then a quick second later, the view will update with the latest fetched data.

Final Thoughts

In this article, we created an Aurora Serverless MySQL database and enabled the Data API feature so that we can interact with our database from an iOS app through a GraphQL API. You might be thinking, what is the benefit of the Data API enabled database? Well, here are my top three benefits of the Data API: 1. You no longer need to create a connection pool or use language-specific drivers to make the connection, authenticate, and invoke the SQL statements. 2. The response from the sql statements is always JSON (mysql query outputs in tabular form as rows and columns) 3. Invocation to the database are direct sql statements via HTTPS versus wrapped/convoluted requests.

The Data API enabled serverless MySQL database is now a “data layer” abstraction, where the underlying NoSQL or SQL engine is not relevant. Much like Parse did with their Core Data abstraction of MongoDB. I bet we’ll soon see a data browser built-in where you can manipulate the data in a web-based table format. I’m super excited about this but let me know your thoughts.