Vapor: Server Side Swift – Noob’s Guide

Author: Jahid Hassan
Tech Lead
Mobility / Android / iOS / Cognitive Systems

Well, if you ended up here I think you are interested in server-side Swift, specially Vapor.

Swift is a beautiful language and Vapor is its perfect company at the server side. Since Swift v2.2 became open source and compatible with Linux at the end of 2015, server-side Swift has been in active development. There are a number of web frameworks written in Swift, including PerfectVaporKitura and Zewo. Among these, Vapor is the simplest. In this post, we will learn how to write a server-side API using Vapor from soup to nuts.

Vapor is a web framework, developed by the collaborators from Qutheory, which stands out for its simplicity, type safety, and speed.

Installation and configuration of Vapor

Before we start with Vapor, we need to configure a few things.
First, we need Swift 3 or later, which is obvious. If you are on macOS you should already have Xcode 8 or later. If not, Install Xcode 8 from the Mac AppStore (https://goo.gl/oqBK0f) or using .xip file from https://goo.gl/wvH864. Xcode comes with the Swift compiler. At the time of writing this post, Xcode version is 8.2.1 and Swift 3.0.2.

Swift installation in Ubuntu is also easy. Type the following command in terminal:

curl -sL swift.vapor.sh/ubuntu | bash

If you want to install manually follow this process.

Now, to check if your system is ready for Vapor, run the following command in Terminal:

curl -sL check.vapor.sh | bash

If everything is correct, install Vapor using this command:

curl -sL toolbox.vapor.sh | bash

From Swift 3.1, the installation command is

brew install vapor/tap/vapor

When the installation is done you will see Vapor’s command line interface, which provides shortcuts and assistance for common tasks.

Make sure the Toolbox installed successfully by running the help query. You should see a print out of the available commands. You can run the --help option on any Toolbox command.

vapor --help

Create and run a Vapor server

Vapor comes with default server template. Create a basic server, using CLI, with a simple command.

vapor new ServerExample

A server template project, named ServerExample will be created. Enter into the project folder using

cd ServerExample

The folder structure of the project will probably look like:

ServerExample
├── Sources
│ └── App
│ └── Controllers
│ └── Middleware
│ └── Models
│ └── main.swift
├── Public
├── Resources
│ └── Views
└── Package.swift

Our main focus will be on the main.swift file.

Now build and run the server with simple commands.

vapor build
vapor run

You will see Server 'default' starting at 0.0.0.0:8080 in the terminal output. If you visit 0.0.0.0:8080127.0.0.1:8080 or localhost:8080 you should see that “it works”:

Let’s check some code. Open the main.swift file using your favorite text editor. A Mac user can use Xcode for editing, build and run the Vapor project. Simply, type vapor xcode in your terminal. Output will be:

Fetching Dependencies [Done]
Generating Xcode Project [Done]
Select the `App` scheme to run.
Open Xcode project?
y/n>

type y and press enter. ServerExample project will open in Xcode. Now, in main.swift you will see following codes:

import Vapor

let drop = Droplet()

drop.get { req in
    return try drop.view.make("welcome", [
            "message": drop.localization[req.lang, "welcome", "title"]
    ])
}
 
drop.resource("posts", PostController())
 
drop.run()

Let’s explain the code a bit.

import Vapor

This standard import declaration of Vapor, which let you access functionalities and symbols defined in Vapor.

let drop = Droplet()

The Droplet is a service container that gives you access to many of Vapor’s facilities. It is responsible for registering routes, starting the server, appending middleware, and more. The Droplet class has a plethora of useful functions on it, and is used extensively.

drop.get

get method creates a Vapor’s Router using Droplet, which handles a GET request.

return try drop.view.make

drop.view.make creates the view and return provides the response when you go to localhost:8080. As it may cause an exception if it is not found, hence try keyword.

 drop.resource

This one gets resource from PostController and registered into the router as a RESTful resource.

And lastly, drop.run() runs the server and listening to the port 8080. This port is defined in servers.json file, which is inside Config folder.