Faerul Salamun
3 min readFeb 10, 2021

--

Hello everyone. In this article, I want to share how to build a Rest API with Fastify and PostgreSQL.

Fastify Logo

Fastify is one of the frameworks for Node.js. From the official website, Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and as far as we know, it is one of the fastest web frameworks in town. If you want to know more about Fastify, you can visit the official website.

Next, we will build a rest API for Create, Read, Update, and Delete User, so prepare your IDE. Create a project structure as shown in the image below.

First, connect to your PostgreSQL and create the database. Run the query in the below :

In the table users, there are 3 fields id, name, and address. Next, we will configure a connection database from Fastify to PostgreSQL. I using Knex in this tutorial. Create file database.js in folder src > helpers.

Don’t forget to create your .env and adjust to your env.

Create a user module. I separate into 4 folders Controller, DTO, Repository, and Service.

Create a file user.repository.js in folder src > modules > user > repository. We will create a code for findAll, findOne, create, update and remove. user.repository.js is used to connect to the database using library Knex.

Create a file user.dto.js in folder src > modules > user > dto.

Next, create a file user.service.js in the folder src > modules > user > service. In this file, we put business logic.

Next, create a file user.controller.js in the folder src > modules > user > controller.

Create a file api.js in folder src > routes. We have 5 routes in this file.

1. GET /api/v1/users fetch data users
2. GET /api/v1/users/:id fetch data user by id
3. POST /api/v1/users create data user
4. PATCH /api/v1/users/:id update data user by id
5. DELETE /api/v1/users/:id delete data user by id

Last we create app.js and server.js. We will use port 3000 for running the API.

Finish, we will test the application use postman. Run command :

node app.js

GET All Users /api/v1/users

GET User By ID /api/v1/users/:id

Post User /api/v1/users

Body :

{
"name":"Faerul Salamun",
"address":"Bandung, West Java, Indonesia"}

Update User /api/v1/users/:id

Body :

{  "name":"Faerul Salamun",  "address":"Indonesia"}

Delete User /api/v1/users/:id

The source code for this tutorial can be found here.

--

--