Kitura Tutorial: Getting Started With Server-Side Swift

Do you wish your iOS skills worked on the backend? This Kitura tutorial will teach you to create RESTful APIs written entirely in Swift. By David Okun.

Leave a rating/review
Download materials
Save for later
Share
Update Note: This Kitura tutorial is now up to date with the latest version of Xcode, version 10.1, and uses Swift 4.2 for development. Update by David Okun. Original tutorial by David Okun.

Are you a busy Swift developer with no time to learn Node.js, but still feel drawn to server-side development? This Kitura tutorial will teach you how to create RESTful APIs written entirely in Swift.

You’ll build a Today I Learned app to help you learn and remember common acronyms like TIL. Along the way, you’ll learn how to:

  • Create a back end API from scratch.
  • Link your API to a CouchDB instance running on your local machine.
  • Assign GET, POST and DELETE routes for a model object.

Getting Started

To complete this Kitura tutorial, you’ll need:

  • macOS 10.14 (Mojave) or higher.
  • Xcode 10.1 or newer.
  • Basic familiarity with Terminal, as you’ll use the command line quite a bit in this tutorial.
Note: It’s possible to use Kitura simply with a text editor and a standalone Swift installation, which makes it possible to run Kitura even on Linux! However, this tutorial uses Xcode to take advantage of autocomplete and the nuances of a familiar development environment.

Installing CouchDB

You’ll use a database called CouchDB in this Kitura tutorial. It’s is a NoSQL database that strictly enforces JSON and uses revision keys for updates. So it’s safe — and fast!

When you’ve finished this tutorial, enter the following command to stop your container:

The --rm in the docker run command will remove the container’s files from your system.

Note: This section shows you how to use Homebrew to install and run CouchDB. If you’d prefer not to install CouchDB directly, and you have Docker installed, you may run it in Docker using the command:
docker run --rm --name couchdb -p 5984:5984 -d couchdb
docker stop couchdb
docker run --rm --name couchdb -p 5984:5984 -d couchdb
docker stop couchdb

Homebrew, a popular package manager for macOS, is the easiest way to install CouchDB. If you don’t have Homebrew installed already, open Terminal and enter this command:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Enter your password if prompted. You should see Installation Successful once it completes.

Next, enter this command to install CouchDB:

brew install couchdb

Once it’s installed, enter this command to start CouchDB:

brew services start couchdb

To confirm that CouchDB is installed and running, open a web browser and navigate to http://localhost:5984. You should see something like this:

{
  "couchdb": "Welcome",
  "uuid": "29b2fe0fb4054c61e6b4b8e01761707b",
  "version": "1.7.1",
  "vendor": {
      "name": "Homebrew",
      "version": "1.7.1"
  }
}

Note: To stop CouchDB, enter brew services stop couchdb.

Before diving into this tutorial, you’ll first need to understand a little about Kitura and REST.

Kitura and RESTful API Routing

IBM created Kitura as an open-source framework in 2015, shortly after Apple open-sourced Swift. They modeled Kitura after Express.js, the de-facto framework for creating RESTful APIs using Node.js.

REST is an acronym for Representational State Transfer. In RESTful apps, each unique URL represents an object. Non-unique URLs represent actions, which are combined with RESTful verbs like GET to fetch objects, POST to insert, DELETE to remove and PUT to update objects.

Backend development often involves many components working together. You’ll only be concerned with two back end components in this Kitura tutorial: the API and database.

For example, if you want to populate a table view with a list of acronyms and their meanings, your client app sends a GET request to the backend. In practice, your app requests the URL http://yourAPI.com/acronyms.

Kitura tutorial client request made to API

The API receives your request and uses a router to decide how to handle it. The router checks all available routes, which are simply publicly accessible endpoints, to determine if there is a GET route ending in /acronyms. If it finds one, it executes the associated route’s code.

The /acronyms route then does the following:

  1. Retrieves the acronyms from the database.
  2. Serializes them into JSON.
  3. Packages them into a response.
  4. Sends the JSON response back to the requesting client.

This results in the following interaction between the API and database:

Kitura tutorial API and database interaction

If an API is RESTful, then it must also be stateless. In this example, you can think of the API as the orchestrator, commanding data to and from your ecosystem. Once the request is fulfilled, the state of the API and its routes should be unchanged and able to handle the next request.

Kitura tutorial API response to client

Just because the API is stateless doesn’t mean it isn’t allowed to store or modify objects. The API itself doesn’t store states, but it does query and update the database to fetch, store and modify objects’ states.

Creating the Kitura Tutorial Project

You didn’t download a starter project for this tutorial yet. Well, that’s because you’re going to create it from scratch, from the command line.

As part of Kitura 2.0, The Swift@IBM team has created a command line interface for Kitura that streamlines generating a similar starter project, without requiring you to write any code yourself! You can try this out (after completing this tutorial, of course) by entering the following commands in Terminal:
brew tap ibm-swift/kitura
brew install kitura
kitura init
brew tap ibm-swift/kitura
brew install kitura
kitura init

Open Terminal and enter the following commands:

mkdir KituraTIL
cd KituraTIL
swift package init --type executable

This uses the Swift Package Manager to create a new executable package.

You should see output similar to the following:

Creating executable package: KituraTIL
Creating Package.swift
Creating README.md
Creating .gitignore
Creating Sources/
Creating Sources/KituraTIL/main.swift
Creating Tests/
Creating Tests/LinuxMain.swift
Creating Tests/KituraTILTests/
Creating Tests/KituraTILTests/KituraTILTests.swift
Creating Tests/KituraTILTests/XCTestManifests.swift

Next, enter the following command to open Package.swift with Xcode:

open -a Xcode Package.swift

Replace the entire contents of Package.swift with the following:

// swift-tools-version:4.2

import PackageDescription

let package = Package(
  // 1
  name: "KituraTIL",
  dependencies: [
    // 2
    .package(url: "https://github.com/IBM-Swift/Kitura.git",
      .upToNextMajor(from: "2.0.0")),
    // 3
    .package(url: "https://github.com/IBM-Swift/HeliumLogger.git",
      .upToNextMajor(from: "1.0.0")),
    // 4
    .package(url: "https://github.com/IBM-Swift/Kitura-CouchDB.git", 
      .upToNextMajor(from: "3.0.0"))
  ],
  //5
  targets: [
    .target(name: "KituraTIL",
      dependencies: ["Kitura" , "HeliumLogger", "CouchDB"],
      path: "Sources")
  ]
)

Here’s what each of these commands does:

  1. You first set the name of your target executable. By convention, you should name this after the enclosing directory.
  2. Here, you declare your dependencies one-by-one; starting with Kitura itself.
  3. HeliumLogger is a back end logging framework, which you’ll use to log messages while your back end app is running.
  4. Kitura-CouchDB allows Kitura to communicate with CouchDB.
  5. Finally, you declare your target and its dependencies.

Save this file and go back to Terminal where you should still be in the same directory containing Package.swift. You are now going to add a document that sets the version of Swift for this project. Enter the following command:

echo "4.2.1" >| ".swift-version"

You are now ready to load your dependencies and build the project for the first time. Enter the following command in Terminal:

swift build

This will generate a lot of logging, ending with logs about compiling your project. You’ll see this output at the end:

Compile Swift Module 'KituraTIL' (1 sources)
Linking ./.build/x86_64-apple-macosx10.10/debug/KituraTIL