Getting Started

Let's develop your first Kitura web application!

First, create a new project directory:

$ mkdir myFirstProject

Next, create a new Swift project using the Swift Package Manager.

$ cd myFirstProject
$ swift package init --type executable

Now your directory structure under myFirstProject should look like this:

myFirstProject
├── Package.swift
├── Sources
│   └── main.swift
└── Tests

info For more information on the Swift Package Manager, visit swift.org.


In Package.swift, add Kitura as a dependency for your project.

import PackageDescription

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

In Sources/main.swift, add the following code.

import Kitura

// Create a new router
let router = Router()

// Handle HTTP GET requests to /
router.get("/") {
    request, response, next in
    response.send("Hello, World!")
    next()
}

// Add an HTTP server and connect it to the router
Kitura.addHTTPServer(onPort: 8080, with: router)

// Start the Kitura runloop (this call never returns)
Kitura.run()

Compile your application:

$ swift build

Now run your new web application:

$ .build/debug/myFirstProject

Open your browser at http://localhost:8080


Add logging (optional)

In the code example above no messages from Kitura will be logged to the console. You may want to add a logger to help diagnose any problems that occur.


Add a HeliumLogger dependency to Package.swift.

import PackageDescription

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

Enable HeliumLogger in Sources/main.swift.

import Kitura
import HeliumLogger

// Initialize HeliumLogger
HeliumLogger.use()

// Create a new router
let router = Router()

// Handle HTTP GET requests to /
router.get("/") {
    request, response, next in
    response.send("Hello, World!")
    next()
}

// Add an HTTP server and connect it to the router
Kitura.addHTTPServer(onPort: 8080, with: router)

// Start the Kitura runloop (this call never returns)
Kitura.run()

Next Steps

Learn how to Deploy your Application to the Cloud.