Server Side Swift Vapor: HelloWorld Web Page Using Leaf

In this article, we will see how to create a simple web page that displays “Hello World” using Server Side Swift framework called Vapor.

1. Working Environment

Xcode : 10.2.1

Swift : 5.0.1

Vapor Toolbox : 3.1.0

Platform : macOS Mojave ( 10.14.5 )

2. Create new project

In this step we will create a vapor project called “HelloWorld”. For this, open a terminal and execute the given below command :

vapor new HelloWorld

3. Generate Xcode Project

Execute the given below commands in terminal :

cd HelloWorld
vapor xcode

Enter ‘y’, for the prompt Open Xcode project?

Now, Xcode will be opened with HelloWorld project.

4. Add Leaf Library to the project

A. Add dependency :

Add the url ( https://github.com/vapor/leaf.git ) in the dependency section of the file Package.swift.

B. Add Target :

Add Leaf in the targets section of the Package.swift

The final Package.swiftfile is given below :

// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "HelloWorld",
    products: [
        .library(name: "HelloWorld", targets: ["App"]),
    ],
    dependencies: [
        // A server-side Swift web framework.
        .package(url: "https://github.com/vapor/vapor.git", from: "3.0.0"),
        
        // Leaf : Html templating framework
        .package(url: "https://github.com/vapor/leaf.git", from: "3.0.0-rc"),

        // Swift ORM (queries, models, relations, etc) built on SQLite 3.
        .package(url: "https://github.com/vapor/fluent-sqlite.git", from: "3.0.0")
    ],
    targets: [
        .target(name: "App", dependencies: ["FluentSQLite", "Vapor", "Leaf"]),
        .target(name: "Run", dependencies: ["App"]),
        .testTarget(name: "AppTests", dependencies: ["App"])
    ]
)

5. Update vapor project

Since we have modified the file Package.swift, we need to update the vapor project to integrate the changes to the project. For this, open terminal and change directory to the project directory and execute the given below command :

vapor update

Enter y, when prompted for Would you like to regenerate your xcode project now?

Enter n, when prompted for Open Xcode project? ( Because Xcode is already opened )

6. Revert code in Xcode

Since the code is changed from outside, Xcode will prompt for Do you want to keep the Xcode version, or revert to the version on disk?

Now press Revert button, in the alert dialog box.

7. Build the Application from Xcode

Before building the application in Xcode, ensure that, Scheme is Run and target device is My Mac.

Set the active Scheme

Once scheme is correctly selected, build the application from the Xcode menu Product->Build

8. Configure Project to use leaf library

In Xcode, open the file Sources/App/configure.swift and add the following to use Leaf templates in the Vapor project.

A. Import Leaf

import Leaf

B. Add the Leaf provider

try services.register(LeafProvider())

C. Set the view renderer

config.prefer(LeafRenderer.self, for: ViewRenderer.self)

The updated Sources/App/configure.swift is listed below:

import FluentSQLite
import Vapor
import Leaf

/// Called before your application initializes.
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
    // Register providers first
    try services.register(FluentSQLiteProvider())
    try services.register(LeafProvider())

    // Register routes to the router
    let router = EngineRouter.default()
    try routes(router)
    services.register(router, as: Router.self)

    // Register middleware
    var middlewares = MiddlewareConfig() // Create _empty_ middleware config
    middlewares.use(ErrorMiddleware.self) // Catches errors and converts to HTTP response
    services.register(middlewares)

    // Configure a SQLite database
    let sqlite = try SQLiteDatabase(storage: .memory)

    // Register the configured SQLite database to the database config.
    var databases = DatabasesConfig()
    databases.add(database: sqlite, as: .sqlite)
    services.register(databases)

    // Configure migrations
    var migrations = MigrationConfig()
    migrations.add(model: Todo.self, database: .sqlite)
    services.register(migrations)
    
    // Set Renderer
    config.prefer(LeafRenderer.self, for: ViewRenderer.self)
}

9. Create Resources/Views folder and add to the Xcode Project

A. Open terminal and change to the project directory and execute the given below command :

mkdir -p Resources/Views

B. In Xcode, add the Resources folder to the Xcode project

Click “Add Files to Helloworld …”
Select Resources folder and Click Add

10. Create View Page index.leaf

Create a leaf template view page namely index.leaf in the folder Resources/Views

<html>
<body>
Hello World
</body>
</html>

11. Setup router

Open the file Sources/App/routes.swift and add the route to view.

import Vapor

public func routes(_ router: Router) throws {
    
    // Route : helloworld renders index.leaf
    router.get("helloworld") { request in
        return try request.view().render("index")
    }
    
}

12. Run the application

A. Run the application by clicking Run button of the Xcode

B. Open a web browser and enter url http://localhost:8080/helloworld

C. Now Hello World will be displayed in the web browser.

13. Download the project

This project can be downloaded from GitHub repository

Comments on this post

No comments.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trackbacks and Pinbacks on this post

No trackbacks.

TrackBack URL