Getting Started with Server Side Swift and šŸ’§Vapor3

Burcu Geneci
Monday Hero
Published in
6 min readFeb 17, 2020
source: https://vapor.codes

Swift is an open source, powerful and expressive language which is safe by design. As an iOS developer, it is fun to use modern features of Swift. This year, in late May, I decided to use that powerful language on our server side project at startup. For me, first, it is an advantage to use swift because of low learning curve, I love having warnings and errors in compile time and feel safe.

In May, Iā€™ve compared Kitura and Vapor frameworks and decided to go for Vapor. Itā€™s was a long comparison but in two words, community and documentation. These were the important factors for me, especially these kind of framework decisions.

After using Vapor 3 & Server side Swift for 9months ā€” 8 months in production, I want to share my experience and highlight some key points.

Let see how different server side swift project in Vapor framework: I will share a github project at the end of the article, so you can use it as a starter project for fast integration.

1 ā€” Installation steps:

I assume that you have already have an Xcode on your MacOS system. So first check system swift version and then install vapor by using brew. If you donā€™t have brew on your system, install it by instruction from here.

swift --version
brew tap vapor/tap
brew install vapor/tap/vapor

You can check your current Xcode and swift version is compatible with vapor, as follows:

eval "$(curl -sL check.vapor.sh)"
Command line result for my current Xcode configuration. Iā€™m Ok to go with Vapor 3, Xcode 10.2 and swift 4.2

2 ā€” Basic Commands:

After completing installation, youā€™re ready to go.āœŒļøThere are some basic commands you should know before starting such as creating vapor project, generating project file and cleaning, building your project.

  • Creating a new project & Generate Xcode project structure

Letā€™s create our very first project, call it VaporApp.

Project names should be PascalCase.

vapor new VaporApp
cd VaporApp
vapor xcode
A warm welcome šŸ˜»
  • Cleaning & Building project

Each time a team member edits package.json for dependencies or adding new files to project file ā€” pbxproj. Thereā€™ll be a need to run vapor clean and vapor update commands.

vapor clean -y
vapor build
vapor update -y

3 ā€” Targets & Project Structure:

vapor xcode command will ask Open Xcode project? Say yes. Youā€™ll see the Xcode project and two schemes of the project: Run scheme and App scheme. Using Run scheme, you will start your project. šŸŽ¬ Then open your favourite browser and go to localhost:8080/hello .Youā€™ll see magic words šŸ”®

http://localhost:8080/hello

When starting Run scheme;

  • main.swift is called, this will create an application instance.
  • configure.swift is called before your application initializes, this is where you need to start services and registered to the app such as db connection, middlewares, router etc.
  • boot.swift is called after application configured,
  • routes.swift is the file,where you can define end point routes that can accept requests.

Vapor projects use Swift Package Manager. Vaporā€™s folder structure builds on top of SPMā€™s folder structure.

SPM Project Structure

So, heading to the route.swift, weā€™ll see a GET router method definition for an endpoint called hello. This closure is where the first request comes and executed. This is the sample endpoint vapor framework creates for you.

Simple GET Endpoint implementation defined in routes.swift

As your vapor app comes bigger, doing implementation in routes file makes things messy. The practical way is using Models for structing content of requests, and implementing logic in Controllers and Services.

Journey of the request through the application architecture

Let's get things complicated, let's say we have greeting endpoint /hello, and it will say hello to people from all over the world, in their language.

  • Request: Has the target url and content. Its basically /hello string in this example.
  • Middleware: Gathers all requests for monitoring or checking header values to control common request values such as language, client version etc. If there is a need for login before using this service, JWTMiddleware is just fine, in this case we can create BaseMiddleware cause of there is no need for login.
  • Controller: Receives request, validates them and send appropriate service or multiple services after extraction its content. In this case, HelloController sends request directly to the GreetingService.
  • Service: Keeps the all logic, talk to database or third party APIs to get things done. GreetingService is responsible for getting the right greeting message from message.json collection.

Letā€™s change initial project structure to following one

As initial project grows, there will be a need for more structured folder system to keep classes in order.

Controllers, Middlewares, Models, Services and finally Extensions

Request & Responses: Letā€™s back to our sample project and create request and response models for getting language of our users and sending getting message. Request and responses should be extended from Content which is Encodable ve Decodable model. In this way, we can get JSON data from our request to GreetingRequest by using decode method and Vapor is automagically encode the response to JSON content while sending it.

Request & Response of hello endpoint

Middleware: Even though there is no need for a middleware for handling requests for this particular case, when the application gets bigger, itā€™s a good check point for handling request headers and so. Letā€™s create our first RequestMiddleware and implement respond method.

Request Middleware for handling requests and check for JWT token and header parameters

Controller: Our lovely HelloController gets request, decode it and send the corresponding service to handle the logic and gets results.

GreetingService: Service layer is responsible for generating greeting message for userā€™s language. Itā€™s a unit for this particular job.

Message:

Message: Service Output model

Service List: ProjectServices holds static definitions of application services.

Application services list.

Routes: Lastly, letā€™s add the route definition and that links sayHello method at HelloController so /greeting/hello request will hit the method.

Weā€™re ready to go, letā€™s try it as follows, sending a POST request to /greeting/hello endpoint.

postman trying vapor 3 post request
Postman request for Hello world! using Vapor 3

Vapor 3 project is ready šŸŽ‰ As I promise, VaporApp github repošŸ‘‡, you can fork as a starting point. Donā€™t forget to star the repo ;)

Have look at vapor framework updates! Vapor have great community on discord.

Next ā€¦

Next blog post will be about using Mongo DB with a Vapor 3 project.

If you enjoy the post, Follow publication on Medium, get notified on the new tech posts.

ā€” Burcu from Monday Hero.

--

--

Burcu Geneci
Monday Hero

Little bit geek, obsessive, keen, funny, mobile, self-starter, self learner or just ā€œdeveloperā€