Server Side Swift with Vapor Post #1 - Introduction to Vapor

Brian Manning published on
8 min, 1503 words

And now for something a bit different... Server Side Swift!

The Swift programming language is the language that powers iOS, macOS, tvOS and watchOS devices... but did you know that it can also be used on Linux, macOS and Windows 10 computers to build web and application servers?

Since the Swift programming language was announced in 2014, multiple web application frameworks written in Swift have been released, and communities have sprung up around these web application frameworks as they have grown and matured.

One of the more popular Swift web application frameworks is called Vapor. The Vapor web application framework makes it easy to build web applications that take advantage of all of the major benefits of the Swift programming language;

  1. Speed
  2. Memory/Type Safety
  3. An expressive language syntax that is "a joy to use"

So Let's Write 🖍 a Vapor App! 👍

So why use Vapor for your next web application? What does Vapor give you to make your life as a web/application developer easier? Will Vapor make your coffee ☕️ for you in the morning? (Hint: no, it won't, but nice try!)

To really see what Vapor can do, let's write a simple Vapor app as an example: a Telegram bot called BitBot!

Telegram is "a globally accessible freemium, cross-platform, cloud-based instant messaging (IM) service" (Wikipedia).

If you can remember the Bit from the original Tron movie, we will make a bot that responds to questions from Telegram users just like the Bit does in the movie.

Project Requirements

To build a Telegram bot using Vapor, you will need some knowledge about how the HTTP protocol works, and some knowledge of the Swift programming language, specifically Swift Optionals, which will be used extensively to model the API messages as they are received from the Telegram API servers.

If you want to run the bot on Telegram, you will need a web server that is accessible from the Internet, which has a valid SSL certificate. If you do not have an SSL certificate, you can use Let's Encrypt to obtain a free SSL certificate for your web server.

Language and Framework Versions

This series of posts on Vapor was written in October of 2022, and will work with any Swift release supported by Vapor version 4 (Swift version 5.2.x and later).

This project will make somewhat heavy use of NSRegularExpression. Yes, Swift 5.7 is out now and it has Regex, but most projects will not be able to start using it right away, so we are using NSRegularExpression for now.

⚓️Ahoy! Lots of Telegram API Info here...

Since this series of posts contains a lot of information about how to use the Telegram Bot API from an application, you may be able to use this series of posts to help you understand how to write your own Telegram bot using a different language/framework than Swift and Vapor.

If this is case, feel free to skip over the Swift/Vapor parts in these posts and concentrate more on the command line commands and the diagrams of various JSON messages that are being sent to/from the Telegram API server by the Vapor bot application.

A Whirlwind 🌪 Tour of Vapor

Probably the first thing that you should know about Vapor is that it has a friendly and helpful community, which you can meet online by joining the Vapor Discord Server.

To give you an idea of how easy and ergonomic it is to write web applications in Vapor, we list below the Vapor components that you would use to implement a basic web application, then describe those components in more detail.

After going over the next few sections on this page, if you like what you have seen of Vapor, you are invited to to check out the Vapor Docs and Vapor API docs pages.

Basic Vapor Stack

The basic "stack" for a Vapor web application would usually have as a minimum, the following components:

  • Routing
  • Content
  • Leaf
  • Logging
  • Environment
  • Web application testing using XCTVapor
  • Fluent (an Object-relational Mapping framework)

In addition to the basic components listed above, Vapor has additional features and frameworks that well suited for building more complex and performant web applications, such as:

  • Middleware
  • Queues
  • Sessions,
  • WebSockets
  • Authentication
  • JSON Web Tokens (JWT)
  • Apple Push Notification Service (APNS)

We won't be using any of these additional components for our Telegram bot, but know that they exist and can be used in your projects. Again, you are encouraged to go over to the Vapor Docs website to see what other features that Vapor provides that can help you write your next web application.

Basic Vapor Components

Routing

Routing is the Vapor component that maps the URLs from incoming requests to the request handlers that handle them. Request handlers are usually are provided by one or more Controllers.

You use Controllers in Vapor to help organize the code in your web application.

The HTTP request methods currently supported by Vapor are GET, POST, PATCH, PUT and DELETE.

Content

The Content API in Vapor implements the Swift Codable protocol, which is used for encoding or decoding data. A Swift struct that conforms to the Content protocol can easily serialize or unserialize itself in an HTTP message.

The Content API is also how Vapor decodes URL query strings. Since query strings in URLs can be optional, members of structs that are created to manage query string data should be Swift Optionals, and you will need to handle these optionals in your application.

Leaf

Leaf is “a powerful templating language with a Swift-inspired syntax”. You can use Leaf to dynamically generate text from a template, such as HTML pages, or the body of an email.

Our Telegram bot does not need to generate HTML or text, all of the bot's responses to the Telegram API server will be JSON data structures generated via the Content protocol, so we will not be using or demonstrating Leaf for this project.

Logging

The Logging API in Vapor is based on SwiftLog, and provides a simple extensible logger with multiple log levels, similar to the log levels provided by most popular syslog implementations.

Environment

The Environment API in Vapor can be used to configure your app dynamically at app startup.

You can change the behavior of your Vapor application at runtime by using Environment to check which environment was specified by the user on the command line.

Environment can also be used load variables into your program at runtime, either by setting environment variables in the startup process environment (FOO="bar"), or by using "dotenv" (.env) files, which are files that contain one or more sets of key/value pairs, one key/value pair per line in the file.

Testing

Vapor comes with multiple extensions to XCTest to help write tests that exercise features of Vapor that you use in your application.

The XCTVapor class comes with a test() helper function which makes it super easy and convenient to write tests for your web application. You can send a test HTTP request to your application, then capture the response from your application in order to run test assertions.

Fluent ORM

Fluent is an Object-relational Mapping (ORM) framework that provides an easy-to-use interface between your Vapor application and a database. There are currently four officially supported drivers for Fluent, PostgreSQL (the recommended driver), SQLite, MySQL, and MongoDB.

Conclusion

We hope that we have given you a good introduction to the Vapor web application framework, and in upcoming posts, we will show you how to use Vapor components listed above to build a Telegram bot.


In the next post, we will list the requirements for our Telegram Bot, and start to think about how to compose a Vapor application that can meet those requirements.

A special thanks to Essential Developer for being a great resource for learning about Swift, iOS and macOS.

Copyright ©2022 by Brian Manning.

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.