Kitura - Server-side SWIFT

What is it?  It's a light-weight web framework written in Swift, that allows you to build web services with complex routes, easily and quickly.
If it's your skillset, it means that you can write Swift client-side (iPad/iPhone) and now write the same syntax code server-side....

Wiki:

https://github.com/IBM-Swift/Kitura/wiki

Features:

URL routing (GET, POST, PUT, DELETE)
URL parameters
Static file serving
JSON parsing
Pluggable middleware

Installation on Mac OSX:

Install SWIFT

The latest version of Kitura works with the DEVELOPMENT-SNAPSHOT-2016-03-24-a version of the Swift binaries.
https://swift.org/builds/development/xcode/swift-DEVELOPMENT-SNAPSHOT-2016-03-24-a/swift-DEVELOPMENT-SNAPSHOT-2016-03-24-a-osx.pkg

You HAVE to use this version, otherwise you will get build errors. Ignore me and waste a few hours, like I did.

Install HOMEBREW

>ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then install the required modules:
>brew install http-parser curl hiredis

MODIFY PATH

Add the following to your PATH:
>nano .profile
export PATH=/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin:$PATH

>source .profile

The reference to 'swift-latest' in the PATH will make sure it points to the latest version you have downloaded and installed.  As mentioned earlier, beware when having multiple version and newer versions installed.

You should now be ready to create your first "Hello World!" application.


MyFirstApp

If you are new to Swift, run this Playground in XCode to get yourself familiar with the Swift programming language.

You'll be surprised at how much you probably already know, it's just the syntax that might be a little different to what you are used to.

Drop into a Terminal, find a suitable folder and type:
>mkdir myFirstProject
>cd myFirstProject
>swift build --init

Now, this is where you might get some errors, if you do, check that your PATH has the correct values above and that you successfully installed the Swift snapshot correctly.  Go check to make sure that there is a /Developer folder inside the /Library folder, that is the first give-away that you didn't install it correctly.

Your folder structure will now look like this:
myFirstProject
├── Package.swift
├── Sources
│   └── main.swift
└── Tests
    └── empty


Modify Package.swift to have the following contents:

import PackageDescription

let package = Package(
    name: "myFirstProject",
    dependencies: [
        .Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 0, minor: 9)
    ])


Modify /Sources/main.swift to have the following contents:

import Kitura
import KituraNet
import KituraSys

let router = Router()

router.get("/") {
request, response, next in
    response.send("Hello Kitaru World!")
    next()
}

let server = HttpServer.listen(8090, delegate: router)
Server.run()


Now compile your application using the following command:
>swift build -Xcc -fblocks -Xswiftc -I/usr/local/include -Xlinker -L/usr/local/lib

>>Compiling Swift Module 'LoggerAPI' (1 sources)
>>Compiling Swift Module 'Socket' (3 sources)
>>Compiling Swift Module 'SwiftyJSON' (2 sources)
>>Compiling Swift Module 'KituraTemplateEngine' (1 sources)
>>Compiling Swift Module 'KituraSys' (4 sources)
>>Compiling Swift Module 'KituraNet' (12 sources)
>>Compiling Swift Module 'Kitura' (13 sources)
>>Compiling Swift Module 'myFirstProject' (1 sources)


>>Foundation.NSNumber:48:30: note: 'init(unsignedLongLong:)' has been explicitly marked unavailable here
>>    public /*not inherited*/ init(unsignedLongLong value: UInt64)
>>                             ^
>><unknown>:0: error: build had 3 command failures
>>error: exit(1): /Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2016-04-12-a.xctoolchain/usr/bin/swift-build-tool
>> -f /Users/tony/Documents/dev/Kitura/Kitura/.build/debug.yaml default
>>make: *** [build] Error 1

Again, if you get build errors like above, then make sure you have the correct Swift snapshot installed.  It will NOT work with the latest version! Go back and get the version I told you to use.

If you need to do a refresh to download the dependencies again, do the following:
>make clean refetch test run

and finally, run your new application:
>.build/debug/myFirstProject

Then, open a web-browser and navigate to:
>http://localhost:8090

You will now see the
"Your Kitura based server is up and running!" message screen, with the "Hello Kitura World!" message at the top of the screen.





Cool!  We've now got the basics working....now let's move on to some more advanced stuff.
In NodeJS, using ExpressJS, we can created REST APIs very quickly and easily.  Here's an example for NodeJS (using the old version of Express, but you get the idea):
>
>
var express = require('express'),
  http = require('http'),
var app = express();

app.configure(function() {
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.set('views', __dirname + '/views');
app.set('libs',__dirname + '/libs');
app.set('scripts',__dirname + '/scripts');
app.set('css',__dirname + '/css');
app.set('images',__dirname + '/images');


//tester API to make sure that the server is listening
app.get('/v1/api',function(request,response) {
    response.send('API is up and running');
});

app.get('/hello',function(request,response){
  response.send("hello from NodeJS");
});

var host = "localhost";
var port = "3000";
var server = app.listen(port, function() {
    console.log('Server running on port %d on host %s', server.address().port,host);
});
process.on('exit', function() {
    console.log('Server is shutting down');
});
>
>
>
In the command-line you would normally have run:
>node myapp.js

and you will now be able to call REST API calls to http://localhost:3000/hello to get a response from the /hello call.




Let's now perform the same thing using Kitura and Swift.....

Create a folder on your Mac to clone the git repo:
>git clone https://github.com/IBM-Swift/Kitura-Sample.git

>cd Kitura-Sample
>make run

This will run the makefile and build the application binary on your Mac.  It will also run the resulting build.  You should see a message ending with:
>>Listening on port 8090



(You did stop the /myFirstProject from listening earlier, didn't you?  If not, switch to that terminal and CTRL+C to stop it running and run the above again)

Alternatively, you can run the same command like before:
>.build/debug/KituraSample

Then, open a web browser and navigate to:
>http://localhost:8090
This will show you the main Kitura page indicating the server is up and running.



>http://localhost:8090/hello
This will echo a hello world message from Kitura, showing that you can implement URL "routes" similar to how you do in NodeJS/ExpressJS that return different information back to the requester.



If you have POSTMAN installed (c'mon, seriously? Got get it now....and slap yourself twice for not doing it sooner.  If you already have it, well done.  Earn 200 goodie-points). Open up and enter the following again - but change to "PUT" instead of a "GET":
>http://localhost:8090/hello



You will see a different message returned indicating you sent a PUT request.  Try the DELETE and POST, just to see what happens.  What this showed is that the backend is able to properly respond to various REST verbs as any good backend server should.

Now, stop the Kitura process by pressing CTRL+C in the Terminal window.




The next step is to run it all in IBM Bluemix!!!
https://developer.ibm.com/swift/products/ibm-bluemix/

Comments