Developing software in the Real World

Kitura tutorial part 5: Hypermedia

In part 4, we looked at configuration, so lets turn our attention back to the API endpoints. We currently have two endpoints in our API: / and /books. While it’s useful to get the entire collection of books, maybe we only want one book. To do this we need a new endpoint: /books/{some unique string}.

In order for the client to know that the URL is to a specific book, we need to tell it by adding a link property to the collection (/books). This is known as Hypermedia.

Adding hypermedia to /books

We’re going to add a structured data format to our API now. For this API, I’ve picked HAL as it provides all the features we need and is reasonably easy to understand. A good explanation of it can be found in Apigility’s HAL primer.

To implement HAL in our response we need to do a number of things:

  1. Add an _links section to the response and include a self link.
  2. Rename the books key to _embedded.
  3. Add an _links section to each book resource within _embedded, again with a self link.
  4. Change the Content-Type to application/hal+json

Let’s take each of these in turn and update the handler:

To add a link section the response we can add it to the JSON object created in our ListBooksHandler. However we need the fully qualified URL.


After var json = JSON([:]), add:

We would be very surprised if the request’s headers collection did not contain a "Host" element as that’s required by HTTP. However, we get back an Optional from the subscript and the simplest way to unwrap it safely is to use ??. We then append "/books" to our baseURL to create the link to self.

Rename books to _embedded

This is simple. we just change:


To add an _links property to each book resource, we edit the closure to



The closure is a little more complex now. Instead of just returning the JSON representation of each book instance, we add a "_links" section. As before, we need a fully qualified URL for the self link, so we use baseURL and then append /books/ followed by the id of the specific book. This creates a unique link for each book.

Change the Content-Type

To change the content type, we set the correct header into the response.

Add this line after the response.status(.OK).send(json: json) call as that will set the Content-Type to application/json automatically.


Test our changes.

Build and run the app. We then use curl as usual to check that our changes have worked:

(I’ve removed most of the embedded resources to make it fit!)

As you can see, each book resource in the _embedded array has a unique link that the client can use to operate on that specific book. The id is quite long as we’ve chosen to make it the concatentation of the id and revision from CouchDB, but of course our client doesn’t care about that.

Now that we have a link to a book resource, let’s write the endpoint that will enable a client to retrieve a single book.

Retrieving a single book

To retrieve a single book, the client needs to send a GET request to a URL of the form /books/{id of this book}. We cannot write a separate route handler for every possible book id as we don’t know them all, but fortunately, we don’t have to as Kitura’s router lets us use a placehold in place of the id string and access it within our handler.

Let’s start by registering our new route in main.swift after the registration of /books:


The route is "/books/:id". The colon before the id tells the router that id is a placeholder and to store the value in the URL into a parameter named id so that the handler can access it later. We name our new handler function getBookHandler and store it in the Handlers directory.

Retrieving a single book from CouchDB

Before we write our handler, let’s look at how we retrieve a book record from CouchDB and wrote a new method, fetchBook(withId:), in our Mapper class. This method goes in BooksMapper.swift after the fetchAll() method:


There’s a lot going on here, so let’s take a look:

Our method takes the book’s id as a string. We specify that we are going to throw errors and that we’ll return a Book instance on success.

The Book’s id is the combination of the CouchDB id and rev values, separated by a “:”, so we split the id on : and assign the first part to bookId which is all we need to retrieve the latest revision of the book.

The retrieve() call fetches a record from CouchDB when you know the id and as with queryByView a closure is called when the method finishes. This closure passes in a JSON document and an error, one of which will be valid and the other nil.

If the data was retrieved by CouchDB, then document will be valid and err will be nil, so we unwrap it and then set bookId to the combination of the CouchDB id and rev values and initialise a Book instance. We assign this to the book variable that we defined outside of the closure so that we can return it to the handler.

If we didn’t have a valid document, then we have an error situation. We assign unwrap err first and then if it’s a 404, we set the Error to NotFound so that we can distinguish it from any other error in the handler. Otherwise, we log what happened as we probably want to know about this error! We don’t log a message for the 404 as that’s not really our problem.

Back in the fetchBook method, after the callback has execute, we throw the error if book is nil, otherwise we know book is valid so we can return it unwrapped.

The Error enum

You probably noticed that we’ve used a couple of RetrieveError contants, so we had better define them. In order to throw an error, we need to define an enum that conforms to the Error protocol. This enum defines the types of errors that we know about and will throw. Add this at the top of the BooksMapper class definition:


This code defines our enum with two values: NotFound and Unknown that we throw in fetchBook().

The handler

We can now turn out attention to the getBookHandler handler function itself:


As usual, we’ll break it down and look at what we’ve just written.

The :id marker in the router’s path definition is available to us in the request.parameters array. This is an Optional, so we guard against it and return a 404 (.notFound) status to the client if the id is missing. Of course, this should never happen… but that’s no reason to not handle it properly!

The fetchBook method throws an error on failure, so we need to wrap it in a do…catch. If we successfully fetch the book, then we get the JSON representation from the Book instance and then add the HAL self link within the \_links array. This is exactly the same as how we did it for the embedded books in the ListBooksHandler function.

We have two error conditions that we want to catch. Firstly, the book’s id may not be found in our database, in which case we set the status code to 400 (.notFound). We also catch any other error condition and return set the status code to 500 (.internalServerError).

As usual, we call next() in order to execute the next handler in the middleware pipeline.


make and run the app and test with curl. Fetch the /books endpoint as before to look up the URL to a specific book and then fetch it:

We now have a working endpoint that represents a single book resource. Next up is to be able to create new books in part 6.

Tutorial navigation

GitHub repository: kitura_bookshelfapi