Learn to Build a Web Application with Swift Language + Vapour

Lawrence Tan 
Jun 21, 2017 · 6 min read

Swift language has really grown throughout the years and it is currently one of the most sought after modern language to learn for complete beginners. Today I am going to guide through a very short tutorial on using this powerful language, to build a simple server that connects to Firebase using Firebase very own REST API. Lets go!

Getting Started with Vapor

Vapor is chosen as my main server-side Swift framework mainly because it has a very helpful community on slack that can help you to solve issues as you develop your application. Here’s the link to get an invitation to their slack team.

Assuming you are using a Mac(which you should, because you are usingApple’s very own language), you can follow this link to install Vapor package on your machine.

You need to :
1. Have Xcode installed
2. Run this script to install/check installation :
curl -sL check.vapor.sh | bash
3. Run this script to install toolbox :
curl -sL toolbox.vapor.sh | bash
4. Verify installation :
vapor --help

Now you are ready to vaporise away to build a Swift Server!

Initialise a new project

Now, we will use newly installed vapour commands to create and initialise a new project.

vapor new TodoList

Then you will be greeted by Vapor!
(Kudos to the team for create such nice ASCII image to welcome us)

Next, lets go into the folder using “cd” and generate an Xcode project using

vapor xcode

You should now see this

This will take awhile, after it is done, hit ‘y’ and you should see your Xcode opened up. Now lets set the scheme and run your very first Vapor Server on localhost!

Try going to your browser and you should be able to run localhost:8080 and receive some feedback on your Xcode console. How cool is that!

Firebase Time
Every server needs a database. I assume that you know how to setup a firebase database, to keep this tutorial short, I will be skipping the setting up of firebase part, you can refer to this link to set one up.

I have a firebase database created with url and rules set in “Rules”

https://[Project-ID].firebaseio.com/{
“rules”: {
“.read”: true,
“.write”: true
}
}

For simplicity, I am skipping Authentication here as well.

I have a very small set of data that I want to pull to display in my Swift hosted server.

It will just be a JSON of data, data of kids with Id and names.

Putting the pieces together (Firebase + Vapor)

When we go back to our Xcode project, we realised that a lot of the files have already been set up for us. For this tutorial we only need to touch Routes.swift, this is where the server will react to the path a user key in on the browser.

Firstly, let create our default url and kid class.

let firebaseBaseUrl = “https://blog-reader
1000.firebaseio.com/kids.json"
class Kid: NodeRepresentable { var firstName: String!
var lastName: String!

func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
“firstName”: self.firstName,
“lastName”: self.lastName
]
)
}
}

A NodeRepresentable is a model protocol recognized by Swift Vapor.
(Check out this link for more info) When a class conforms to this protocol, we are able to make a Node Model that can be used in Vapor.

Secondly, we will need to target a specific path/route that will trigger the event to call Firebase URL. The main brain of such functionality is inside

extension Droplet {
func setupRoutes() throws {
}
}

We want the route to be something like “localhost:8080/kids/all”, hence we will use group to create a main path (kids) and a sub path (all). We realise that as we walk along the paths of vapor, we see a lot of closures coming in.

group(“kids”) { tasks in
tasks.get(“all”) { request in
}
}

Here we see group creating a new object which I call it “tasks” so that inside this group, I can hold a reference to the next task which is to call a get method in the sub path “all” to do something. And here is where I will use a separate client object to do an external http call

return try self.client.get(firebaseBaseUrl)

So now if I do a get request on the url “http://localhost:8080/kids/all” with the server running, I can get my first data response from Firebase. HURRAY!

Restlet Client

What a great achievement!

Alright, let’s now end this tutorial by inserting data into our Firebase database.

We will use post request to do this. And we will create a path call “http://localhost:8080/kids/create” using post closure.

post(“kids”, “create”) { req in
}

Using the guard statements we learnt in Swift, lets do a bit of error handling :

guard
let firstName = req.json?[“firstName”]?.string,
let lastName = req.json?[“lastName”]?.string else {
throw Abort.badRequest
}

We see something new here call req.json which will actually pick out the json object from our POST body and parse it into the string with a valid key. We also see Abort, another Vapor’s own error object to throw to user if either of the string is not available.

Next, to post it back to firebase, we need to create a stringyfied body from like this :

let body = “{\”firstName\”: \”\(firstName)\”, \”lastName\”: \”\(lastName)\”}”.makeBody()

Makebody is another protocol method that is inside the String extension file. It returns a Vapor’s body object that holds the data to be sent.

Once this is done, lets get our client again to send to firebase!

let response = try self.client.post(firebaseBaseUrl, query: [“”: “”], [“Content-Type”: “application/json”], body, through: [])

For this request, we only need to focus on :
1. url
2. body
3. headers

Once done, lets run my Restlet client again to throw a POST request!

Viola! 200 OK and our newly added data is in Firebase!

And here’s the end of this short tutorial, exploring server-side swift is an amazing journey as we can see how modern languages like Swift can build a fast-running server in a very short time. Do not hesitate do drop me a comment here or hit the love button if you would like more of such tutorials!

Here’s a link to the full project.

Before you go…

MindOrks

Our community publishes stories worth reading on software development and design. Android | Machine Learning | #MakeEveryoneCode

Lawrence Tan 

Written by

Mobile Application Developer @ MSD. Loves God, My Fiance, Family & Corgis. Freelance Writer when not coding.

MindOrks

MindOrks

Our community publishes stories worth reading on software development and design. Android | Machine Learning | #MakeEveryoneCode

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade