Sample server code using Vapor framework.

Basic Swift Server Setup Using Vapor

Ever since Apple announced and released the Linux compatible Swift source code, server side Swift has been one of the most active development pursuits. A lot of frameworks have come out including Perfect, Vapor, and Kitura (by IBM). In this blog post, we will discuss how easy it is to make a basic setup using Vapor.

Vapor is a web framework for Swift developed by the collaborators from Qutheory. It boasts of its simplicity, type safety, and speed. The framework gets updated frequently to work with the latest Swift 3 snapshots. Currently, development testing are being done on OSX and Ubuntu (14.04 and 15.10).

We will setup a server that will run locally using the latest Vapor release as of writing.

Installing Swift 3

swiftenv install DEVELOPMENT-SNAPSHOT-2016-05-03-a

This command downloads and installs the May 3, 2016 Swift 3 snapshot.

Installing the Vapor CLI

wget -O vapor
chmod +x vapor
sudo mv vapor /usr/local/bin

Updating the CLI is as simple as

vapor self-update

Creating the server

vapor new test-server // Creates a project named "test-server"
cd test-server
vapor build
vapor run

Running the given commands will setup a basic server template and run it. If you visit http://localhost:8080 on your browser you will see something like this.

Vapor sample landing page.

It’s a simple project example which you can then modify to suit your server needs. Vapor even provides examples by clicking on the links on the landing page.

Custom Routes

Xcode toolchain selection

The project should have the following file structure. Open main.swift to create a custom application route.

Xcode project hierarchy

Just beneathe the line where the application was instantiated, we are going to create a custom route named greeting.

let app = Application()app.get("greeting) { request in
return "Welcome, user!"

We need to halt (CTR +C) the current running server and rebuild the app to integrate our current changes.

vapor build && vapor run

The currently running server should reflect the changes we have made to the code.

Now, we’ll implement a route that gets the user’s name. Notice how we are passing another argument besides the route name to indicate that we are expecting a String parameter.

app.get("greeting", String.self) { request, name in
return "Welcome, \(name)!"

Rebuild and rerun the server and you should get the following output.

Final Thoughts

Vapor and all the other libraries under Qutheory are in a very active development stage. They are also inviting other developers to contribute to the codebase since everything is open sourced on github.