قالب وردپرس درنا توس
Home / Apple / Kitura Tutorial: Getting Started with Server-Side Swift

Kitura Tutorial: Getting Started with Server-Side Swift



Update note : This Kitura guide is now updated with the latest version of Xcode, version 10.1, and uses Swift 4.2 for development. Update by David Okun. Original training by David Okun.

Are you a busy Swift developer with no time to learn Node.js, but still feel drawn on server-side development? This Kitura tutorial will teach you how to create RESTful APIs completely written in Swift.

You are going to build a Today I learned the app to help you learn and remember common acronyms like TO . Along the way, you will learn how to:

  • Create a background API from scratch.
  • Connect the API to a CouchDB instance running on your local machine.
  • Assign GET POST and DELETE routes for a model object.

Getting Started

To complete this Kitura tutorial, you must:

  • macOS 1
    0.14 (Mojave) or higher
  • Xcode 10.1 or later.
  • Basic knowledge of Terminal, which you will use the command line quite a bit in this tutorial.

Note : It is possible to use Kitura easily with a text editor and a standalone Swift installation, which makes it possible to run Kitura even on Linux! However, this tutorial uses Xcode to utilize autocomplete and nuances of a known development environment.

Installing CouchDB

You use a database called CouchDB in this Kitura tutorial. It is a NoSQL database that strictly enforces JSON and uses audit keys for updates. So it's safe – and fast!

Note : This section shows how to use Homebrew to install and run CouchDB. If you prefer not to install CouchDB directly and you have Docker installed, you can run it in Docker using the command:

docker run --rm - name couchdb -p 5984: 5984 -d couchdb

When you finish this tutorial, type the following command to stop your container:

  docker stop couchdb

- rm in the command docker-run removes the container's files from your system.

Homebrew a popular package handling for macOS, is the easiest way to install CouchDB. If you do not have Homebrew already installed, open Terminal and enter this command:

  / usr / bin / ruby ​​-e "$ (curl -fsSL https://raw.githubusercontent.com / homebrew / install / master / installation) "

Enter your password if prompted. You should see Installation Successfully when finished.

Then type this command to install CouchDB:

  bridge installation sofa

Once installed, enter this command to start CouchDB:

  brew services start couchdb

To confirm that CouchDB is installed and running, open a web browser and navigate to http: // localhost: 5984. You should see something like this:

  {
"couchdb": "Welcome",
"uuid": "29b2fe0fb4054c61e6b4b8e01761707b",
"version": "1.7.1",
"seller": {
"name": "Homebrew",
"version": "1.7.1"
}
}

Note: : To stop CouchDB, enter brewing services, stop couchdb .

Before entering this tutorial, you must first understand some of Kitura and REST.

Kitura and RESTful API Routing

IBM created Kitura as an open-source framework in 2015, shortly after Apple opened Swift. They modeled Kitura after Express.js, the de facto framework for creating RESTful APIs using Node.js.

REST is an acronym for Re presentation S tate ransfer. In RESTful apps, each unique URL represents an object. Non-unique URLs represent actions that are combined with RESTful verbs such as GET to retrieve objects, POSTs to insert, DELETE to remove, and PUT to update objects.

Backend development often involves many components that work together. You will only be concerned with two back components of this Kitura tutorial: API and database.

For example, if you want to fill in a table view with a list of acronyms and their meanings, your client app sends a GET request to the backend. In practice, the app asks you for the URL http://yourAPI.com/acronyms .

 Customer request from Kitura made to API

The API receives your request and uses a router to determine how to handle it. The router checks all available routes that are only publicly available endpoints to determine if there is a GET route ending in / acronyms . If it finds one, it executes the corresponding route code.

The / Acronyms route then does the following:

  1. Retrieves acronyms from the database.
  2. Serialize them in JSON.
  3. ]
  4. Send the JSON response back to the requesting client. This results in the following API-database interaction:

     Kitura Guidance API and Database Interaction

    If an API is RESTful, it must also be stateless . In this example, you can think of the API as orchestrator, which controls data to and from your ecosystem. Once the request is met, the state of the API and its routes should be unaltered and able to handle the next request.

     Kitura guide API response to client

    Just because the API is stateless It does not mean that it is allowed to store or modify objects. The API does not store states but queries and updates the database to retrieve, store, and modify object states.

    Creating the Kitura Training Project

    You did not download a startup project for this tutorial yet. Well, that's because you're going to make it from the bottom of the command line.

    As part of Kitura 2.0, The Swift @ IBM team has created a command line interface for Kitura that streamlines to generate a similar startup project without requiring you to write any code yourself! You can try this out (after completing this tutorial of course) by entering the following commands in Terminal :

    brew tap ibm-swift / kitura
    brew installation kitura
    kitura init
    

    Open Terminal and enter the following commands:

      mkdir KituraTIL
    cd KituraTIL
    quick package init type executable
    

    This uses Swift Package Manager to create a new executable package.

    You should see the output similar to the following:

      Create executable package: KituraTIL
    Create Package.swift
    Creates README.md
    Create .gitignore
    Creating sources /
    Create sources / KituraTIL / main.swift
    Create samples /
    Create tester / LinuxMain.swift
    Create test / KituraTILTests /
    Create Test / KituraTILTests / KituraTILTests.swift
    Create test / KituraTILTests / XCTestManifests.swift
    

    Next, enter the following command to open Package.swift with Xcode:

      open-a Xcode Package.swift
    

    Replace the entire contents of Package.swift with the following:

      // swift-tools version: 4.2
    
    import package description
    
    let package = package (
    // 1
    name: "KituraTIL",
    dependencies: [
        // 2
        .package(url: "https://github.com/IBM-Swift/Kitura.git",
          .upToNextMajor(from: "2.0.0")),
        // 3
        .package(url: "https://github.com/IBM-Swift/HeliumLogger.git",
          .upToNextMajor(from: "1.0.0")),
        // 4
        .package(url: "https://github.com/IBM-Swift/Kitura-CouchDB.git", 
          .upToNextMajor(from: "3.0.0"))
      ],
    // 5
    Goal: [
        .target(name: "KituraTIL",
          dependencies: ["Kitura" , "HeliumLogger", "CouchDB"],
    path: "Sources"
    ]
    )
    

    Here's what each of these commands do:

    1. You first enter the name of your target. By convention you should mention this by the attached folder.
    2. Here you declare the addictions one by one; starts with Kitura himself.
    3. HeliumLogger is a backend logging framebook that you want to use to log messages while the back of the app is running.
    4. Kitura-CouchDB allows Kitura to communicate with CouchDB.
    5. Finally, you declare your goal and its dependencies.

    Save this file and return to Terminal where you should be in the same directory containing Package.swift . You should now add a document that specifies the version of Swift for this project. Enter the following command:

      echo "4.2.1"> | ".Swift version"
    

    You are now ready to load your dependencies and build the project for the first time. Enter the following command in Terminal :

      swift build
    

    This will generate a lot of logging, and ends with logs to collect your project. You see this output at the end:

      Compile Swift Module & Kit # 39; KituraTIL & # 39; (1 source)
    Linking ./.build/x86_64-apple-macosx10.10/debug/KituraTIL
    

    Troubleshooting Error

    If you get errors from Quick Build enter the following in Terminal to confirm your Swift version:

      Quick Release
    

    If your version is lower than Swift 4.2.1, this is probably your problem. To fix this, make sure you have the latest version of Xcode 10 installed, and then run the following command:

      sudo xcode-select -s /Applications/Xcode.app
    

    … where Xcode.app should be replaced the path to Xcode 10.

    If you still have problems, you may use swiftenv or another Swift version management tools, and you may need to manually set the Swift version to 4.2.1.

    Here is the command to do this if you use swiftenv :

      swiftenv global 4.2.1
    

    Using Kitura With Xcode

    In Terminal in the root directory of the training project, enter the following command:

      quick package generate-xcodeproj
    

    You should see this output:

      generated: ./KituraTIL.xcodeproj
    

    Enter this command to open your new Xcode project:

      xed.
    

    You will then be faced with this view:

    From here, make sure the selected target unit is My Mac . After selecting it, build and run ( Command + R ) your Xcode project, and you will see this printed on the console:

      Hey, the world!
    The program ended with the output code: 0
    

    Awesome! : If you see the warning Conversion to Swift 4.2 is available please get your rear end app up! press it. There should be no changes needed. Just click Update again to change their building settings.

Setting Up Your Kitura Server

You only need a few lines of code to configure your server with a router and a logger. [19659002] First create a new Swift File called Application.swift in the group Sources / KituraTIL group folder – the folder containing main.swift ]. Be sure to add this file to KituraTIL executable target:

Next, replace the contents of this file with the following:

  import Kitura
import loggerAPI

public class App {

// 1
leave router = Router ()

public func run () {
// 2
Kitura.addHTTPServer (onPort: 8080, with: router)
// 3
Kitura.run ()
}
}

Here's what this does:

  1. The router will handle incoming requests by directing them to the correct endpoints.
  2. Here you register the router to run on port .
  3. .
  4. .

    With your App class created, open

    . . Kitura runs endlessly on the main loop after calling ] main.swift and replacing the contents with the following:

      import Kitura
    import HeliumLogger
    import loggerAPI
    
    HeliumLogger.use ()
    
    leave app = App ()
    app.run ()
    

    The command HeliumLogger.use () sets up HeliumLogger as the default logger for Kitura. It is good practice to log in early and log often .

    Then, create an App example and run it.

    Build and run, and you should see log messages from Kitura displayed in the console.

    Then navigate to http: // localhost: 8080 in your browser and you should see this page:

    Congratulations, you are now running a basic Swift-based HTTP server on your local machine !

    Creating Your Model

    In this section, you will create a model type that represents an acronym.

    Create a new Swift file Acronym.swift and remember to add it to KituraTIL the goal.

    Replace the contents of this file with the following:

      // 1
    import CouchDB
    
    // 2
    structure Acronym: Documents {
    // 3
    la _id: String?
    // 4
    was _rev: String?
    // 5
    was short: String
    was long: strict
    }
    

    This is what you have done:

    1. You must import this module so you can make structure according to the protocol Document

      .

    2. By creating Acronym in accordance with Document you will be able to utilize both Codable Routing and CouchDBs Document Protocol. You will learn more about Codable Routing cards, but Document allows you to take advantage of the latest database driver for CouchDB.
    3. As with most database drivers, you have a document protocol requires this.
    4. CouchDB will also alert you to the latest revision of a document to confirm any updates or delete actions you perform on an entry so that Document protocol requires this property _rev .
    5. Finally, the object itself requires that you save both a long form and a short-form acronym for this tutorial.

    ] Build your project to make sure everything looks good. Remember, again, double-checking that the new files are part of the KituraTIL goal!

    Note that your object matches the protocol Document . This is a mechanism that forces objects that can be read by the CouchDB database driver, also in accordance with Codable which will be very useful during the journey with server-side Swift. Codable is simply a typealias combining the protocols Encodable and Decodable and Decodable . This ensures that matching objects can be converted both to and from external representations. In particular, Kitura uses this to easily convert instances to and from JSON.

    Before Kitura 2.0, you had to send a query object into each endpoint shutdown, manually analyze properties, cast correctly, perform necessary transformations, and finally make JSON send in response. There was much of work!

    You can now utilize the power of Kitura's Codable Routing to significantly reduce the boiler plate code in routes. Win! You just have to do your models according to Codable to take advantage of this, as you did above.

    With this theory out of the way, it is now time to connect the API to CouchDB. [19659013] Connect CouchDB

    Open Application.swift and replace the contents with the following:

      // 1
    import CouchDB
    import the foundation
    import Kitura
    import loggerAPI
    
    public class App {
    
    // 2
    was client: CouchDBClient?
    var database: Database?
    
    leave router = Router ()
    
    private func postInit () {
    // 3
    }
    
    private func createNewDatabase () {
    // 4
    }
    
    private func finalizeRoutes (with database: Database) {
    // 5
    }
    
    public func run () {
    // 6
    postInit ()
    Kitura.addHTTPServer (onPort: 8080, with: router)
    Kitura.run ()
    }
    }
    

    Reviewing these changes:

    1. You first import CouchDB to set up your persistence layer.
    2. You add the client properties to the CouchDB and database to keep track of changes.
    3. You add code here after you have created your instance of App to connect to your database.
    4. If postInit () method
    5. After configuring the database, you will enter all available routes for your API to match against here.
    6. You call postInit () from run () to do this part of your API setup.

    Next, complete postInit () by replacing // 3 with the following.: 1919659058] / 1
    la connectionProperties = ConnectionProperties (host: "localhost",
    port: 5984,
    secured: false)
    client = CouchDBClient (connectionProperties: connectionProperties)
    // 2
    client! .DrB ("Acronym") {database, error in
    guard la database = database otherwise {
    // 3
    Log.info ("Could not retrieve acronym database:"
    + "(String (describes: error? .LocalizedDescription))"
    + "- trying to create a new one.")
    self.createNewDatabase ()
    return
    }
    // 4
    Log.info ("Acronyms database is located - loads ...")
    self.finalizeRoutes (with: database)
    }

    This is what you just did:

    1. You create a ConnectionProperties object that you use to set configuration values ​​and a new CouchDBClient


      Source link