Client-side code should be as simple and concise as possible, and with a new library called KituraKit, developing web applications using REST has never been easier.

Built on top of the new features introduced in the latest Kitura 2.0 release, KituraKit offers an API for calling REST requests, with support for Swift 4’s new Codable protocol using Codable Routes.

What is REST?

Every request on the web needs a HTTP method such as POST or GET, and a URI that the method is routed to. How this incoming HTTP method is dealt with is called routing, and Kitura helps define what happens during routing for URIs you set up.

Say you set up a Kitura Server with the following code:

import Kitura
let router = Router()
Kitura.addHTTPServer(onPort: 8080, with: router)
Kitura.run()

Your server is now up and running in 3 lines of code (or less if the Router() is declared within the function!), and it’s listening for incoming HTTP methods such as the ones mentioned above, plus a few more. How the server delegates after it receives this method is what KituraKit aims to make as easy as possible. You initialize a KituraKit object in your application with the following declarations:

import KituraKit
let client = KituraKit(baseURL: "http://localhost:8080")

The creation of the client means we can start adding some logic to determine what happens when certain REST calls are made. For example what happens when you want to send something to your server? We created a demo application for iOS, consisting of both a front end app and a backend server. The demo is called ToDo, and the following method is called when a user taps the ‘Save’ button in the iOS app after entering some details to make a new ToDo item:

func create(title: String, user: String, order: Int) {

  let newToDo = ToDo(title: title, user: user, order: order, completed: false)
  self.client?.post("/", data: newToDo) { (returnedItem: ToDo?, error: Error?) -> Void in
  print(String(describing: returnedItem))

  guard returnedItem != nil else {
    print("Error in creating ToDo. error code \(String(describing:error))")
    return
    }
  }

This method is doing a few things, but in a nutshell it created a new ToDo item from the fields the user entered in the app, and then POSTs the data to the server, using the client which is a KituraKit object. Let’s walk though this part of the method in more detail:

self.client?.post("/", data: newToDo) { (returnedItem: ToDo?, error: Error?) -> Void in

It calls the POST HTTP method on KituraKit, which takes two parameters, a route “/” and some data to POST, in this case newToDo. After the input parameters comes a closure, defining two things, returnedItem of ToDo? type and an error of Error? type. Both are optional, because depending on how the server deals with the request, the POST can either be a success and have a return of the thing that was POSTed, or an error. That’s it!

The server would have to handle the incoming POST request and send back either the returnedItem or the error.

Type Safety in KituraKit

A great feature of KituraKit is it’s inherent type safety. The returnedItem is of type ToDo?, so the server is actually dealing with concrete types that match your client side code. This is part of the beauty of Codable in Swift 4. As all objects passed in need to have concrete types to match the server, there’s no type inference or confusion about what may have been passed in, reducing crashes and mismatches between both ends. This ultimately ensures a safer and less crash-prone experience when creating apps that interface with the server. Preventing type errors can stop a plethora of bugs where the wrong types of operations could be performed on the data passed in.

Reality itself contains type safety, as weights can’t be added to lengths, or heights to widths. Type safety is becoming more and more popular in modern programming languages and Swift’s enforcement of types means your code is less prone to mismatches, and therefore bugs and crashes.

Time to REST

Other REST calls such as READ, PATCH, UPDATE, and DELETE can also occur via Kitura’s client-side routing, which make use of corresponding functions within the code. These are all handled in a type safe manner with Codable routes. These all take in a route “/” and some data to be POSTed, along with an identifier at times to be able to easily access and identify server-side items. The DELETE call invoked via a self.client?.delete() method does not have any data passed in as it merely performs a deletion on the root of the route that is provided to it.

As these REST calls are wrapped in simple and familiar functions, there’s less multi-platform knowledge required by the user, whilst also remaining powerful enough to allow manipulation of data on the server as freely as ever. Less work to get the same end results, it’s a win win!


Special thanks to Shihab Mehboob, another member of the Swift@IBM team for contributing to this blog post!

2 comments on"KituraKit: Client-side REST made easy"

  1. My swift project needs to retrieve data from a rest service via HTTPS. Therefore it uses the URLSessionDelegate from the module Security to verify the certificate with certificate pinning (comparing the expected certificate with the provided certificate).

    The problem is that on the Linux platform the latest Swift 4.0 still does not offer the module Security. Therefore the URLSessionDelegate is not available.

    How to achieve certificate pinning with Kitura to gurantee that I talk to the correct server?

Leave a Reply