Kitura Logo

USING KITURA CREATE

OVERVIEW

The kitura create command is a command-line tool that provides a guided question-and-answer way to create Kitura Swift applications.

The generator supports two different ways to generate an application: scaffolding a starter and generating a CRUD application.

Scaffolding a starter

A scaffolded starter is an application containing boilerplate code but little or no application logic. You can use this as a base for your application by modifying the generated files with your application logic.

You can select from a number of different options presented by the generator to define extra content to be included in the resulting application. For example, these include things like adding the boilerplate for serving static files and creating connections to databases.

Generating a CRUD application

A CRUD (Create-Read-Update-Delete) application is one where you provide a description of a data model and the generator creates application code for a REST webservice that will provide endpoints to perform create, read, update and delete operations for data matching that data model. In the current version of the generator, most of the generated CRUD application is not open for modification or extension—expect this to change in a future version to allow for more flexibility.

Installation

macOS

Follow the Getting Started.

Ubuntu Linux

Prerequisities

Complete the following steps to install Swift Server Generator

npm install -g yo
npm install -g generator-swiftserver

Swift Server Generator is supported only on the following operating systems:

Getting Started

First, run the Kitura application generation (see Command line tools):

kitura create

Enter swiftserver-getting-started as the application name.

What's the name of your application? swiftserver-getting-started

Tip: You can use a different name for the application, but if you do, be sure to substitute your name for swiftserver-getting-started throughout the rest of this tutorial.

Press Enter to accept the default directory for the project (the same as the application name).

Enter the name of the directory to contain the project: (swiftserver-getting-started)

Select Scaffold a starter at the type of project prompt and press Enter.

Select type of project: (Use arrow keys)
❯ Scaffold a starter
  Generate a CRUD application

Select Web at the application pattern prompt (this determines the default set of capabilities) and press Enter

Select capability presets for application pattern: (Use arrow keys)
  Basic
❯ Web
  Backend for frontend

Press Enter to accept the default capabilities for the Web application pattern.

Select capabilities: (Press {space} to select, {a} to toggle all, {i} to inverse selection)
❯ ◉ Static web file serving
  ◯ Swagger UI
  ◉ Embedded metrics dashboard
  ◉ Docker files

Press Enter to accept the default of not generating code from a swagger specification in the scaffolding.

Select endpoints to generate: (Press  to select, {a} to toggle all,  to inverse selection)
❯ ◯ Swagger file serving endpoint
  ◯ Endpoints from a swagger file

Press Enter to accept the default of not generating a Swift server SDK from a swagger file in the scaffolding.

Would you like to generate a Swift server SDK from a Swagger file? (y/N)

Press Enter to accept the default of not including any boilerplate for services in the scaffolding.

Generate boilerplate for services: (Press  to select, {a} to toggle all,  to inverse selection)
❯ ◯ Cloudant / CouchDB
  ◯ Redis
  ◯ MongoDB
  ◯ PostgreSQL
  ◯ Object Storage
  ◯ AppID
  ◯ Auto-scaling

The generator will display messages as it scaffolds and builds the application including:

  • 1. Initializing the project folder structure.
  • 2. Creating and compiling default Swift files.
  • 3. Downloading and installing dependent Swift modules (as if you had manually run swift build).

Now you should have a generated application directory similar to this:

swiftserver-getting-started/
├── public/
├── Sources/
│   ├── Application
│   │   ├── Application.swift
│   │   ├── Metrics.swift
│   │   └── Routes/
│   │       └── HealthRoutes.swift
│   └── swiftserver-getting-started
│       └── main.swift
├── Package.swift
├── README.md
├── config.json
└── ...

For a description of the generated files, take a look at the structure of a generated project in the Project layout reference.

Change to the application directory:

cd swiftserver-getting-started

Start the application:

.build/debug/swiftserver-getting-started

Confirm the application is running locally by opening the URL http://localhost:8080 in your browser. You’ll see something like this:

Welcome to Kitura
Your Kitura based server is up and running!

Congratulations, you now have a simple Kitura web application ready for extension with your own application logic. Now you can:

  • 1. Review and modify the generated code.
  • 2. Create web content in the public directory.
  • 3. View the embedded metrics dashboard on http://localhost:8080/swiftmetrics-dash.

Core Concepts

The kitura create command creates a Kitura Swift application based on the project type, capabilities and services you select. To do this, use the command-line tools provided by installing the generator.

Project type

The project type defines whether the generated application is a scaffold or CRUD application.

Scaffold

This project type is for creating a starter application where you define all of the application logic yourself. The generator will create the directory structure and boilerplate code based on the capabilities and services you select.

You may modify any of the generated code and will not be expected to run the generator again on the generated project.

CRUD

This project type is for creating a CRUD (Create-Read-Update-Delete) application where you provide a description of a data model and the generator creates application code for a REST webservice that will provide endpoints to perform create, read, update and delete operations for data matching that data model.

The data model is specified by using the model generator on the generated project to create each piece of the data model, or by using the property generator on the generated project to modify existing pieces.

Throughout the documentation we will use the following terminology:

  • “data model” — the data model as a whole (eg: the bookstore data model)
  • “model” — a piece of the data model (eg: the book model)
  • “property” — a property of a model (eg: the title of a book)
  • “entity” — a particular set of data matching a model (eg: a book with title “War and Peace”)

Each time the data model is modified, parts of the project are regenerated to match the updated definition and the application will be rebuilt with swift build.

When you define a model it automatically comes with a predefined REST API with a full set of create, read, update, and delete operations. This REST API is described in more detail in Exposing Swift Server Generator models over REST.

You can create models by using the model generator, which creates a Model definition JSON file that defines your model. By convention, this file is located in the project’s models directory; for example, models/bookstore.json.

After a model and its properties have been defined, an OpenAPI (Swagger 2.0) specification is also generated that describes and documents the REST APIs. By convention, this is located in the project’s definitions directory; for example, definitions/bookstore.yaml.

You should not modify the code in the Sources/Generated directory, or the OpenAPI Swagger definition file in the definitions directory as any modifications will be lost when these files are regenerated.

Capabilities

Capabilities define chunks of functionality that will be implemented by the generated application. The application generator will ask you to select the capabilities you would like included.

For the scaffold project type, you can select from the following list:

  • Static web file serving
  • Swagger UI
  • Embedded metrics dashboard
  • Docker files

For the CRUD project type, you can select from the following list:

  • Embedded metrics dashboard
  • Docker files

The list allows for toggling of any combination of the available capabilities which will start with a default set selected.

The default set will depend on the project type:

  • CRUD project type: all 3 available capabilities are selected by default
  • Scaffold project type: defaults depend on application pattern

Web capability

This capability will include a public directory in the root of the project. The contents of this directory will be served as static content using the built-in Kitura StaticFileServer module.

This content is hosted on /. For example, if you want to view public/myfile.html and the application is hosted at https://localhost:8080, go to https://localhost:8080/myfile.html.

This capability is only available for scaffold projects.

Metrics dashboard capability

This capability uses the SwiftMetrics package to gather application and system metrics.

These metrics can be viewed in an embedded dashboard on /swiftmetrics-dash. The dashboard displays various system and application metrics, including CPU, memory usage, HTTP response metrics and more.

Docker capability

This capability includes the following files for Docker and Kubernetes support:

  • .dockerignore
  • Dockerfile
  • Dockerfile-tools
  • chart

The .dockerignore file contains the files/directories that should not be included in the built docker image. By default this file contains the Dockerfile and Dockerfile-tools. It can be modified as required.

The Dockerfile defines the specification of the default docker image for running the application. This image can be used to run the application.

The Dockerfile-tools is a docker specification file similar to the Dockerfile, except it includes the tools required for compiling the application. This image can be used to compile the application.

The chart folder contains pre-configured Kubernetes resources for this project. It allows the use of Helm to streamline the deployment of a docker image to the cloud.

To build the two docker images, run the following commands from the root directory of the project:

docker build -t myapp-run .
docker build -t myapp-build -f Dockerfile-tools .

You may customize the names of these images by specifying a different value after the -t option.

To compile the application using the tools docker image, run:

docker run -v $PWD:/root/project -w /root/project myapp-build /swift-utils/tools-utils.sh build release

To run the application:

docker run -it -p 8080:8080 -v $PWD:/root/project -w /root/project myapp-run sh -c .build-ubuntu/release/{app_executable}

Server SDK generation

This is the capability to generate a server SDK library from a swagger specification document, which can be used to allow the generated server application to call APIs on an external service. Providing the swagger document for the external service allows client-side Swift API stubs to be generated into the Routes directory.

Endpoints

Swagger fileserving endpoint capability

This capability adds an endpoint to the application to provide file serving of an OpenAPI Swagger definition file for this application. This assumes that a pre-prepared Swagger document has been written and will be placed at definitions/{app_name}.yaml.

The endpoint is hosted on /swagger/api. For example, if the application is hosted at https://localhost:8080, go to https://localhost:8080/swagger/api.

This capability is only optional for scaffold projects and is always enabled in CRUD projects.

If the SwaggerUI capability and Swagger endpoint capability are enabled then specification of this interface is made available through an embedded Swagger UI hosted on /explorer. For example, if the application is hosted at https://localhost:8080, go to https://localhost:8080/explorer. The Swagger UI will document the paths and http methods that are supported by the application.

Endpoints from swaggerfile capability

This capability will generate example or custom API endpoint code from an OpenAPI (swagger) document. If selected, then the fileserving endpoint capability is automatically enabled.

Example endpoints capability

This capability includes an OpenAPI Swagger definition and routes for a Product example resource. The OpenAPI Swagger definition is located at definitions/{app_name}.yaml.

Endpoints from swagger file

The user can choose to generate endpoints by specifing the path or URL to a swagger specification document.

This capability is only available for scaffold projects.

SwaggerUI capability

This capability uses an embedded Swagger explorer web page to load and display the OpenAPI Swagger definition in the user friendly explorer web page. Through the explorer page, the user can view and exercise the APIs documented within the Swagger document.

Services

The services offered by the generator will depend on the project type and capabilities you have selected.

For CRUD project type no services are available except those that are implied by the CRUD store prompt.

IBM Cloud services

These services are hosted on IBM Cloud and the application can connect to them either locally or when deployed to IBM Cloud.

When IBM Cloud services are selected, a set of deployment configuration files to support deploying your application to IBM Cloud are created:

  • manifest.yml
  • .bluemix/toolchain.yml
  • .bluemix/pipeline.yml

The manifest.yml defines options which are passed to the Cloud Foundry cf push command during application deployment.

IBM Cloud DevOps service provides toolchains as a set of tool integrations that support development, deployment, and operations tasks inside IBM Cloud. The “Create Toolchain” button in the README.md creates a DevOps toolchain and acts as a single-click deploy to IBM Cloud including provisioning all required services.

You need to publish your project to a public github.com repository to use the “Create toolchain” button.

Cloudant IBM Cloud service

This service uses the Kitura-CouchDB package, which allows Kitura applications to interact with a Cloudant or CouchDB database.

CouchDB speaks JSON natively and supports binary for all your data storage needs.

Boilerplate code for creating a client object for the Kitura-CouchDB API is included inside Sources/Application/Application.swift as an internal variable available for use anywhere in the Application module.

The connection details for this client are loaded by the configuration boilerplate code and are passed to the Kitura-CouchDB client.

Redis IBM Cloud service

This service uses the Kitura-redis library, which allows Kitura applications to interact with a Redis database.

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports a cracking array of data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries.

Boilerplate code for creating a client object for the Kitura-redis API is included inside Sources/Application/Application.swift as an internal variable available for use anywhere in the Application module.

The connection details for this client are loaded by the configuration boilerplate code and are passed to the Kitura-redis client.

PostgreSQL IBM Cloud service

This service uses the Swift-Kuery-ORM which allows Kitura applications to interact with a PostgreSQL database.

Boilerplate code for creating a client object for the Swift-Kuery-ORM is included inside Sources/Application/Application.swift as an internal variable available for use anywhere in the Application module.

The connection details for this client are loaded by the configuration boilerplate code and are passed to the PostgreSQL client.

Object Storage IBM Cloud service

This service uses the Object Storage package to connect to the IBM Cloud Object Storage service.

Object Storage provides an unstructured cloud data store, which allows the application to store and access unstructured data content.

Boilerplate code for creating a client object for the Object Storage API is included inside Sources/Application/Application.swift as an internal variable available for use anywhere in the Application module.

The connection details for this client are loaded by the configuration boilerplate code and are passed to the Object Storage client.

AppID IBM Cloud service

This service uses App ID package to connect to the IBM Cloud App ID service.

App ID provides authentication to secure your web applications and back-end systems. In addition App ID supports authentication using social identity providers so that users can login with their existing user accounts, such as Facebook and Google.

Boilerplate code for creating a client object for the App ID API is included inside Sources/Application/Application.swift as an internal variable available for use anywhere in the Application module. Extra routes and logic need to be added to make this a authentication boilerplate work. A working example can be found in the App ID README.

The connection details for this client are loaded by the configuration boilerplate code and are passed to the App ID client.

Auto-scaling IBM Cloud service

This service uses the SwiftMetrics package for connecting to the IBM Cloud Auto-scaling service. You can use this to automatically manage your application capacity when deployed to IBM Cloud. You will need to define the Auto-Scaling policy (https://console.ng.bluemix.net/docs/services/Auto-Scaling/index.html) to define the rules used to scale the application.

The connection details for this client are loaded by the configuration boilerplate code and are passed to the SwiftMetrics auto-scaling client.

Watson Conversation IBM Cloud Service

This service uses the Watson Swift SDK package, which allows Kitura applications to build Watson-powered applications, specifically in this case the IBM Watson Conversation service.

With the IBM Watson Conversation service you can create an AI assistant that combines machine learning, natural language understanding, and integrated dialog scripting tools to build outstanding projects, such as a chat room with an integrated Watson chat bot.

Boilerplate code for creating a client object for the Watson Conversation API is included inside Sources/Application/Application.swift as an internal variable available for use anywhere in the Application module.

The connection details for this client are loaded by the configuration code and are passed to the Watson Conversation client in the boilerplate code.

More information about the Watson Conversation can be found in the README.

Alert Notification IBM Cloud Service

This service uses the Alert Notification Service SDK package, which allows Swift developers to utilize the Alert Notifications service in their applications, allowing for the proactive remediation of issues for applications running on IBM Cloud. Alerts and messages can be created, received and deleted through the use of this SDK.

This SDK is for the consumption/usage of the Alert Notification service and not for administration of the service. Adding users, groups, notification policies, etc. should be done through the IBM Cloud dashboard.

Boilerplate code for creating a client object for the Alert Notification API is included inside Sources/Application/Application.swift as an internal variable available for use anywhere in the Application module.

The connection details for this client are loaded by the configuration code and are passed to the Alert Notification client in the boilerplate code.

A quick start guide to the Alert Notification Service on IBM Cloud can be found here.

A quick start guide to the Alert Notification Service on IBM Cloud can be found here.

This service uses the Push notifications package, which is a Swift server-side SDK for sending push notifications via the IBM Cloud Push Notifications service.

Boilerplate code for creating a client object for the Push Notifications API is included inside Sources/Application/Application.swift as an internal variable available for use anywhere in the Application module.

The connection details for this client are loaded by the configuration code and are passed to the Push Notifications client in the boilerplate code.

More information about the Push Notifications Service can be found in the README.

Prompt Reference

The following sections describe the prompts provided by the application generator.

Application name prompt

If you did not supply an application name as an argument, the application generator will ask the name you would like to use for your application:

What's the name of your application? (currentDirectory)

The default value is the name of the current working directory.

The application name you enter must satisfy the following constraints:

  • Must not start with a .
  • Must not contain whitespace characters
  • Must not contain any of the following characters: /@+%:
  • Must not contain characters reserved in URIs
  • Must not be node_modules
  • Must not be favicon.ico

Application directory prompt

The application generator will ask the name of the directory you would like to use for your application:

Enter the name of the directory to contain the project: (applicationName)

The default value is the name of the application.

If the directory name is the same as the current directory, then the generator will assume you want to create the project in direcly in the current directory rather than creating a subdirectory of the same name.

The application directory you enter must satisfy the following constraints:

  • Must not contain whitespace characters
  • Must not contain any of the following characters: /@+%:
  • Must not contain characters reserved in URIs

Project type prompt

The application generator will ask which type of project you would like to create, offering two options:

  Select type of project: (Use arrow keys)
❯ Scaffold a starter
  Generate a CRUD application

The Scaffold a starter option will direct the generator to create a scaffolded application providing boilerplate code and application structure to which your application logic can be added.

The Generate a CRUD application option will direct the generator to create a CRUD application on top of which a data model can be defined which will automatically be mapped to REST endpoints for create, read and update operations. At present the code for this type of application is not very customizable aside from modifying the data model.

Application pattern prompt

For scaffolded applications, the application generator will ask which application pattern you want to select, offering three options:

  Select capability presets for application pattern: (Use arrow keys)
❯ Basic
  Web

The application pattern defines the capabilities that are selected by default in the subsequent capabilities prompt. They are presets and the capabilities they suggest can be modified as required.

Basic pattern

The Basic pattern is intended for any type of application, making the fewest assumptions about the application logic. Selecting this pattern will result in the following defaults for the capabilities prompt:

◯ Static web file serving
◯ Swagger UI
◉ Embedded metrics dashboard
◉ Docker files

Web pattern

The Web pattern is intended for an application that needs to provide a web server hosting static files. Selecting this pattern will result in the following defaults for the capabilities prompt:

◉ Static web file serving
◯ Swagger UI
◉ Embedded metrics dashboard
◉ Docker files

BFF pattern

The Backend-for-frontend (BFF) pattern is intended for an application that provides a microservice intended for consumption by a client application (for example, a web or mobile application). Selecting this pattern will result in the following defaults for the capabilities prompt:

◉ Static web file serving
◉ Swagger UI
◉ Embedded metrics dashboard
◉ Docker files

Capabilities prompt

The application generator will ask which capabilities you want to select.

For Scaffold project type, the following capabilities are available:

  Select capabilities: (Press {space} to select)
❯ ◯ Static web file serving
  ◯ Swagger UI
  ◉ Embedded metrics dashboard
  ◉ Docker files

For CRUD project type, the following capabilities are available:

  Select capabilities: (Press  to select)
❯ ◉ Embedded metrics dashboard
  ◉ Docker files

The list allows for toggling of any combination of the available capabilities which will start with a default set selected.

CRUD project type always enables the OpenAPI / Swagger endpoint

The capabilities selected by default when this prompt is shown depend on the project type:

  • CRUD project type: all 3 available capabilities are selected by default
  • Scaffold project type: defaults depend on application pattern

Services prompt

For scaffolded applications, the application generator will ask which services you want to select.

  Generate boilerplate for services: (Press  to select)
❯ ◯ Cloudant / CouchDB
  ◯ Redis
  ◯ MongoDB
  ◯ PostgreSQL
  ◯ Object Storage
  ◯ AppID
  ◯ Auto-scaling
  ◯ Watson Conversation
  ◯ Alert Notifications
  ◯ Push Notifications

CRUD store prompt

For CRUD applications, the application generator will ask how you want to store entities:

  Select data store: (Use arrow keys)
❯ Memory (for development purposes)
  Cloudant / CouchDB

Selecting Memory (for development purposes) will mean entities are stored in a simple memory-based database.

The memory data store is volatile and any data added will be lost when the application is stopped. As such, it is only suitable for development purposes.

Selecting Cloudant / CouchDB will add a local CouchDB service for entity storage.

Service configuration prompt

The application generator will ask you which of the services you selected need to be configured, for example:

  Configure service credentials (leave unchecked for defaults): (Press  to select)
❯ ◯ Cloudant / CouchDB
  ◯ Redis
  ◯ Object Storage

Any services you do not select in this prompt will use default values.

For each service you select, a set of custom prompts will ask for the relevant connection details to be supplied.

Slack icon

NEED HELP?

MESSAGE US ON SLACK.