Look Maa! Server Side Swift Using Vapor
At WWDC 2016 Apple demonstrated the power of server side Swift using the IBM Kitura framework. I have spend the last 10+ years implementing server side code using Microsoft ASP.NET so, the idea of server side anything really intrigeud me as a developer.
Currently, as an iOS developer you have several choices to build your own backend. This includes Firebase, CloudKit, Realm Mobile Platform or use any of the popular server side technologies like Ruby on Rails or ASP.NET Web API. The problem with using CloudKit and Firebase is that they may not exist tomorrow. Parse is a perfect example of a platform which allowed iOS developers to create backend using Objective-C/Swift code served hundreds and thousands of users but was shut down by Facebook. The same could happen to CloudKit or Firebase.
The safest route for creating a backend system is to build it yourself. The problem is that most iOS developers lack the skills and knowledge to create backend systems using different frameworks and languages. Server side Swift is going to allow them to use the same programming language to create their backend API’s.
Vapor requires Xcode 8 to be installed. You can download Xcode 8 from the Mac App Store. Once, downloaded make sure double click on the Xcode file and install it. You can double check the installation by running the following command.
curl -sL check.vapor.sh | bash
Next install the Toolbox. And thats pretty much it! You are ready to create your first awesome Vapor application.
Vapor command line tools allows to easily and quickly create applications. Just run the following command to create a blank Vapor project.
vapor new hello-vapor
If everything is installed correctly you will see the following screen conforming that the project was created successfully.
Now you can jump into the “hello-vapor” folder and run the following command to setup Vapor Xcode project and download all the dependencies.
Be patient! This might take a while :)
Once, you have downloaded the dependencies select “yes” to open the project in Xcode. Since, this is server side Swift you will have to run the server to run the application. Select the “App” scheme from the scheme drop down list and run the app.
Keep you eye on the output window because it is going to display the URL on which the server is running. Once, the server has started simply visit the URL http://localhost:8080/ and you will be greeted with the welcome page as shown below:
Congratulations! You got Vapor!
In this section we are going to see how we can create GET requests using the Vapor framework. Open “main.swift” which is contained inside the App folder and replace the code with the following:
The above code is going to create a route “hello” which, when invoked returns the string “Hello Vapor!”. Start the server by clicking on the play button and then visit the following URL.
The result is shown in the following screenshot:
Pretty sweet right!
You can even have nested URLs. Let’s say you have a list of customers but you also want to pass in the id of the customer to get a particular customer.
The result is shown below:
Returning data in String format is great but if we need to return structured data then we must return it in either JSON or XML format. Luckily Vapor provides helper functions to easily return JSON formatted data.
And the result is shown below:
That’s nice but in real life we have objects and it would be great if we can return objects as JSON. Not to worry Vapor makes it simple to convert classes into JSON representation. Take a look at the following implementation:
The Customer class conforms to the NodeRepresentable protocol. NodeRepresentable protocol allows the class to represent itself as a Node. This is performed by using the makeNode function as demonstrated above.
The result is shown below:
GET requests are awesome but if you want to create content, you need to POST data. Luckily posting data to the Vapor service is pretty straight forward. Take a look at the following implementation:
The request.json? dictionary contains all the data being sent with the POST request. In the code above we extracted the “firstName” and the “lastName” values and stored them in the “firstName” and “lastName” variables. In the end we are returning the concatenated string of the firstName and lastName values.
At this point you can use any HTTP Client to invoke the route. I used a Mac App called “HTTP Client” as shown below but feel free to use any HTTP Client you desire.
Pretty sweet right!
It would be super awesome! If we can actually store the data into some sort of database. In the next section I am going to show you how to configure and connect Vapor to SQLite3 database.
Configuring SQLite3 Database
Vapor allows to connect to several different kind of databases through the use providers. Since, we are trying to connect to SQLite database we will need Vapor SQLite provider which is available here.
There are few required steps to configure the Vapor SQLite provider. First, you must update the Package.swift file in your Vapor project to include a link to the provider. This is demonstrated below:
You also need to add a “sqlite.json” file inside the “Config” directory of your Vapor project. The “sqlite.json” file will contain the name and the path of the SQLite database.
The “HelloVaporDB.sqlite” will be available at the root of the project. Don’t worry about the database right now, we will create it later. At this point you need to download the packages for SQLite. This can be done using the command line.
Now, open your Xcode project and import “VaporSQLite” module and also register the “VaporSQLite” as a provider.
Congratulations! Now you are ready to unleash the power of SQLite in your app! The implementation below shows the “version” route which returns the current version of SQLite on your system.
The result is shown below:
The above screenshot is a confirmation that we are able to install the SQLite provider successfully. In the next section I am going to show you how you can insert real data into the SQLite database.
Inserting Data into SQLite Database
The first thing we need for our quest to insert data into the database is the .. database. You can use any application you want to create a SQLite database. I am going to use Base, which is available for purchase here. The schema for our database is shown below:
Make sure to copy the “HelloVaporDB.sqlite” in the root of your Vapor project.
Let’s jump to the “main.swift” file and start implementing our route to insert new customer. The initial part of the function will be similar to the POST route that we implemented earlier. The actual insertion is done by the SQLite provider.
The result is shown in the HTTP Client below.
And in the database.
Server side Swift is still a new technology and is actively being developed by IBM, Vapor and other teams. Server side Swift AKA SSS allows the developers to free themselves from third party frameworks like Firebase, CloudKit, Realm, Backendless etc. I am really excited about server side Swift and I think it will play an integral role in moving Swift forward.
You can download the complete project here.
Recently I published a course on Udemy called “Mastering Server Side Swift Using Vapor”. The course covers everything you need to know about the Vapor framework. Check below for details.
The course original price is $195 but if you use the link below you can get the course for ONLY $50. THAT’S 74% INSTANT SAVINGS.