Currently in Beta - View old docs

Kitura Server Style Guide

This guide covers a way of structuring your project code to make future development easier and keep your project files looking clean.

Prerequisites

  • Kitura Server: Learn how to create one in our Getting Started guide.

Recommended Project Structure

We recommend you follow the Model-View-Controller (MVC) design pattern for your Kitura project (with controllers in our case called routes). An example file structure for a project following this patten is:

    MyKituraApp
    ├── Package.swift
    ├── Sources
    │    ├── MyKituraApp
    │    │    └── main.swift
    │    └── Application
    │         ├── Application.swift
    │         ├── Routes
    │         │    └── HealthRoutes.swift
    │         ├── Models
    │         │    └── Book.swift
    │         └── Middlewares
    │              └── CheckoutSession.swift
    ├── Views
    │    └── Template.stencil
    ├── public
    │    └── Img.jpg
    └── Tests
         └── ApplicationTests
    

If you used the Kitura CLI, or Kitura macOS app, to create your project your files will already be in this structure.

This might seem a bit complex, so let's break down what these folders and files are:

  • Package.swift – defines packages that your app depends on and their versions
  • main.swift - the file that is run to initialize your app and run your server
  • Application.swift - the application that glues everything together
  • Routes – (also known as controllers) defines your app routes and their logic
  • Middlewares – Kitura middlewares which process the incoming requests before handing them down to the routes
  • Models – represents data, implements business logic and handles storage
  • public – contains all the static files like images, styles and javascript
  • Views – provides templates which are rendered and served by your routes
  • Tests – contains the Swift tests for your project

Throughout these guides we will assume you have a project set up as described above. If you generated your project with the Kitura macOS app or Kitura CLI, skip ahead to Step 5: Defining a Book model. If you generated your project using the Swift Package Manager (SPM), the following steps will produce the above structure.

Step 1: Create the Application directory

Within our `Sources` directory we first need to create an `Application` directory:

mkdir Sources/Application

This is the directory where we will store all of our application code.

Next we will create our `Application.swift` file:

touch Sources/Application/Application.swift

Next we need to create our Routes directory :

mkdir Sources/Application/Routes

This is where we will store all of our route handlers.

Next we will rename the directory within Tests to ApplicationTests:

mv Tests/MyKituraAppTests/ Tests/ApplicationTests

Step 2: Update Package.swift

Next we need to configure our `Package.swift` file to synchronize with the new project structure:

// swift-tools-version:4.2
  import PackageDescription

  let package = Package(
    name: "MyKituraApp",
    dependencies: [
      .package(url: "https://github.com/IBM-Swift/Kitura.git", from: "2.6.0")
    ],
    targets: [
      .target(name: "MyKituraApp", dependencies: [ .target(name: "Application"), "Kitura"]),
      .target(name: "Application", dependencies: [ "Kitura" ]),

      .testTarget(name: "ApplicationTests" , dependencies: [.target(name: "Application"), "Kitura" ])
    ]
  )

Now we can rebuild our project:

swift build

If you are on macOS and would like to work within an Xcode project then you need to regenerate your Xcode project:

swift package generate-xcodeproj

You may need to reopen the Xcode project for these changes to take effect.

Step 3: Add code to the Application.swift file

Earlier, we created the `Application.swift` file but we didn't add any code to it.

Open the `Application.swift` file in our default text editor:

open Sources/Application/Application.swift

The `Application.swift` file will be responsible for starting our Kitura server.

Add the following code to the `Application.swift` file:

import Kitura

  public class App {

      let router = Router()

      public init() throws {

      }

      func postInit() throws {

      }

      public func run() throws {
          try postInit()
          Kitura.addHTTPServer(onPort: 8080, with: router)
          Kitura.run()
      }
  }

Step 4: Add code to the main.swift file

Now that we have created our `App` class in our `Application.swift` file we can use it within our `main.swift` file.

Open the `Sources/MyKituraApp/main.swift` file and replace the existing code with the following:

import Application

  do {
      let app = try App()
      try app.run()

  } catch let error {
      print(error.localizedDescription)
  }

Step 5: Defining a Book model

As we are simulating a bookstore in our guides, we are going to need to define a book. The book is a model so the first thing we need to do is create our Models folder:

mkdir Sources/Application/Models

This is the directory where we will store all of our models.

Next we will create our `Book.swift` file:

touch Sources/Application/Models/Book.swift

We will open the `Book.swift` file in our default text editor:

open Sources/Application/Models/Book.swift

Inside this file we define our Book:

struct Book: Codable {
      let id: Int
      let title: String
      let price: Double
      let genre: String

      init(id: Int, title: String, price: Double, genre: String) {
          self.id = id
          self.title = title
          self.price = price
          self.genre = genre
      }
  }

Next steps

Add logging: Get useful feedback from your server about startup and errors.

Add routing: Add REST APIs, such as HTTP GET, to your server.

Back to top