How to Install Postgres Driver in Vapor 2


The default sqlite database that is included with vapor has no data persistence, therefore, to get data persistence, we need to setup a local database, and install a driver in our vapor project, so our vapor project can talk to our local database. This tutorial will focus on how to do so with Postgresql.

Part 1: Add the dependency

First, in your Package.swift file, add this to your dependencies array:

   Package(url: "", majorVersion: 2)

Now close your Xcode project, return to the terminal, and run $ vapor update. After this, you will see in the terminal this prompt:

    Changes to dependencies usually require Xcode to be regenerated.
    Would you like to regenerate your xcode project now?

Type "y" to regenerate the Xcode project, with your new dependency. Open the Xcode project again upon completion.

Part 2: Configure your Xcode project

Next, in Config+Setup.swift , add the import statement for the driver:

   import PostgreSQLProvider

Still in Config+Setup.swift, add the following to the setupProviders() method:

   try addProvider(PostgreSQLProvider.Provider.self)

Next, in the Config folder, create a new file, and call it postgresql.json. In that file, copy and paste the following:

       "hostname": "",
       "user": "",
       "password": "",
       "database": "",
       "port": 5432

(We will soon fill these values correctly)

Next, go to fluent.json. Change the line:

    "driver": "memory"


    "driver": "postgresql"
Part 3: Create a local Postgres database (note: this assumes you already have Postgres installed on your mac):

Open the terminal, and run the command

   $ createdb postgrestutorial

In postgresql.json, change the "database" key to be:

    "database": "postgrestutorial"

For the value of "user", run the command $ whoami in the terminal. And then fill in your password for postgres that you made when originally installing postgresql on your computer.

That's it! To test, you can make a POST request to http://localhost:8080/posts, with a body of {"content": "testing content"} using Postman, or another HTTP rest client. Then, restart the server, make a GET request to http://localhot:8080/posts, and your post data should be persisted across restarts. In my case, the output for a GET to http://localhost:8080/posts was:

          "id": 1,
          "content": "testing content"

Post questions/comments below!