Category Archives: Swift

There are lot of server side swift frameworks. The popular frameworks on GitHub are Perfect, Vapor, Kitura.

We will Create a small todo app using Postgres database, Will see how to implement simple routes and basic CRUD operations using Vapor framework.

Vapor :

This is the second most popular framework on GitHub for swift. Vapor provides best documentation and it build in swift3. And it will be a great staring point to start server side swift.  Vapor had all the packages that needed by an app and it has a very supporting community.

Reasons to use vapor :

  • Vapor uses web sockets to make real-time connections.
  • JSON Serialisation
  • Ability to create Controllers and Models.
  • Extensible, It uses Middlewares to add any parameters to HTTP requests. and we can add more functionalities
  • Expressive, The static type system allows you to write less and do more

Before getting started we need have these things

  1. Mac running on latest Os(Mac OS 10.12, Sierra)
  2. Xcode 8 or above
  3. Basic understand of swift language and iOS SDk

Getting started

Install Xcode : Install Xcode from App store

Install Vapor :

  • Compatibility Check : To check that your environment is compatible run the following script in terminal

  • If you get the green check mark, then you are all set to install vapor
  • Install vapor toolbox : Run the following command to install Vapor

    it might take a while. and finally we will get the message Vapor Toolbox v1.0.5-4-gd20c424 Installed

  • To check Vapor is working, just type the vapor command in your terminal and it will display like this                                                                          

Install Postgres : The easiest way to install Postgres is through Homebrew. If homebrew is not installed, download it from the link. Install Postgres using this command

Type the following command, to ensure that you have downloaded postgres

 

Starting a new vapor project :

We a building a simple todo app which can add, update and delete a todo. We will give api’s to do basic crud operations. Open terminal, And Cd to the directory of your choice and type the command.

This will create a new Todo Project

The directory will look like this

vapor creates a the Package.swift, here we can add any dependencies for the project. Then in the App folder, we can see main.swift, Controllers and Models.

The main.swift file is our main app file, where we can initialise and run the server

The resources folder contains the views, which contains and html and template files.

We can easily create Xcode project using vapor toolbox. Go to project directory type the command

This command will fetch the dependencies for the project and will take some time. After fetching all the dependencies it will ask you to open project in Xcode, type y and enter to open the project in Xcode

In Xcode project navigate to Source/App/Main.swift

We can see the code like this

This main.swift file imports the Vapor framework, and initiates the Droplet

Droplet, is a service that have access to Vapor functionalities. It is backbone of our server and it responsible for running server . So we import the vapor in main.swift and created an  intense of droplet.

The droplet will handle many properties, get the documentation from here 

Create a route: Now  create a route, a get request which returns the list of todos and finally run the drop.

Now run the Xcode project, make sure that you have selected app schema.

Run the application from Xcode to get the app running on localhost on port 8080. After Successfully building and running the app in Xcode. you can see  Server ‘default’ starting at 0.0.0.0:8080 in logs 

Now open the browser or post man and navigate to  http://localhost:8080/todos, we can see the list of todo’s

Create a Todo model :

Its good to have a Todo model, to avoid hard coding values. Vapor is providing model protocol, this will help us to convert models to JSON easily

vapor framework includes Fluent framework, which is ORM tool for swift that will work with different databases.

Cerate a file Todo.swift

The first property we will set is Id, this property will contain the identifier when model is fetched from DB, if it is nil it will set after when we save to DB.

Node Initializable :

we need to create a model from persistence data, model uses NodeInitializable to archive this data.

Node Representable :

NodeRepresentable will help us to save it back to database

Preparation :

We need to create a table for our Todo class, we will crate table using this prepare method. here we have created the todos Table .

Revert : 

this is the reversion of prepare method, this will be run using this command

Here it will delete the table todos.

Now we have seen how to create a route and model. Lets connect to Postgres database to create more routes

Setting up Postgres:

  • add the postgres provider url to Package.swift file

  •  
  • Regenerate Xcode project to download the postgres dependencies
  • Import the VaporPostgreSQL in main.swift file,
  • Append the Todo.self to drop preparation so that we can use model with Database
  • Then add provider to droplet so that database is available

     
  • Create a configuration file for Postgres, create the following file: Config/secrets/postgresql.json and update the file with these values, use your own username for  “user”
  • Creating Postgres Database, Run the Postgres server locally by using this command

    • Open another terminal and Create the database using this command
    • Type psql <Table name> command to get Postgres command line interface. Now we can check out routes by using postman. and plsql commands

Now we will create routes, which will perform the CRUD operations

AddTodo Route:

Now we are creating Add todo route using Postgres for adding todo and saving it to DB

In this route, we have created a new instance of todo from request (req.json), which is passed from post request.

Save that created instance using save() command.

This is post route is expecting body like this

GetTodo By ID Route :

Here, Int.self 2nd argument in the path so the url will be todo/1, so that we can send parameters in route.

We are using Fluent, So We can Easily use find(_:) , to get the instance of model

UpdateTodo By ID Route:

This is the route to update todo by using its Id. Here we will get id by Int.self and request parameters. We are getting the instance by using ID, and updating values in it and saving back to DB.

Delete Todo Route :

Here we are finding the model by using id and deleting it from DB.

Conclusion :

In this tutorial we covered, how to install vapor, Xcode, Postgres and Created API’s For Simple CRUD operations.  This server side swift is new technology and actively being developed by IBM, perfect an vapor teams.

This post will help to getting started with server side swift with Vapor.