Hello, World
This section assumes you have installed Swift 3 and the Vapor CLI and have verified they are working.
New Project
Let's start by creating a new project called Hello, World
vapor new Hello
Folder Structure
Vapor's folder structure will probably look familiar to you if you have worked with other web frameworks.
.
├── App
│ └── Controllers
│ └── Middleware
│ └── Models
│ └── main.swift
├── Public
├── Resources
│ └── Views
└── Package.swift
For our Hello, World project, we will be focusing on the main.swift file.
.
└── App
└── main.swift
Open main.swift in your favorite text editor.
Example Project
The
vapor newcommand creates a new project with examples and comments about how to use the framework. You can delete these if you want.
Droplet
Look for the following line in the main.swift file.
let drop = Droplet()
This is where the one and only Droplet for this example will be created. The Droplet class has a plethora of useful functions on it, and is used extensively.
Routing
Right after the creation of drop, add the following code snippet.
drop.get("hello") { request in
return "Hello, world"
}
This creates a new route on the Droplet that will match all GET requests to /hello. All route closures are passed an instance of Request that contains information such as the URI requested and data sent. We will learn more about requests later.This route simply returns a string. We will learn more about what can be returned by route closures later.
Starting
At the bottom of the main file, make sure to start your application.
drop.serve()
Save the file, and switch back to the terminal.
Compiling
A big part of what makes Vapor so great is Swift's state of the art compiler. Let's fire it up. Make sure you are in the root directory of the project and run the following command.
vapor build
Toolbox Shortcut
vapor buildrunsswift buildin the background.
The Swift Package Manager will first start by downloading the appropriate dependencies from git. It will then compile and link these dependencies together.When the process has completed, you will see output similar to Linking .build/debug/App
Process Killed
If you see a message like
unable to execute command: Killed, you need to increase your swap space. This can happen if you are running on a machine with limited RAM.
Run
Boot up the server by running the following command.
vapor run serve
# Optionally specify port
vapor run serve --port=8080
You should see a message Server starting.... You can now visit http://localhost/hello in your browser.
Permission Denied
Certain port numbers require super user access to bind. Simply run
sudo vapor runto allow access. If you decide to run on a port besides 80, make sure to direct your browser accordingly.
Hello, World
You should see the following output in your browser window.
Hello, world
Updated less than a minute ago
