Node.js Express & PostgreSQL: CRUD Rest APIs example with Sequelize

Node.js Rest CRUD API overview

We will build Rest Apis that can create, retrieve, update, delete and find Tutorials by title.

First, we start with an Express web server. Next, we add configuration for PostgreSQL database, create Tutorial model with Sequelize, write the controller. Then we define routes for handling all CRUD operations (including custom finder).

The following table shows overview of the Rest APIs that will be exported:

Methods

Urls

Actions

GET

api/tutorials

get all Tutorials

GET

api/tutorials/:id

get Tutorial by id

POST

api/tutorials

add new Tutorial

PUT

api/tutorials/:id

update Tutorial by id

DELETE

api/tutorials/:id

remove Tutorial by id

DELETE

api/tutorials

remove all Tutorials

GET

api/tutorials/published

find all published Tutorials

GET

api/tutorials?title=[kw]

find all Tutorials which title contains 'kw'

Finally, we’re gonna test the Rest Apis using Postman.

This is our project structure:

node-js-express-sequelize-postgresql-project-structure

Create Node.js App

First, we create a folder:

Next, we initialize the Node.js App with a package.json file:

We need to install necessary modules: express, sequelize, pg, pg-hstore and body-parser. Run the command:

*pg for PostgreSQL and pg-hstore for converting data into the PostgreSQL hstore format.

The package.json file should look like this:

Setup Express web server

In the root folder, let’s create a new server.js file:

What we do are: – import express, body-parser and cors modules:

  • Express is for building the Rest apis

  • body-parser helps to parse the request and create the req.body object

  • cors provides Express middleware to enable CORS with various options.

– create an Express app, then add body-parser and cors middlewares using app.use() method. Notice that we set origin: http://localhost:8081. – define a GET route which is simple for test. – listen on port 8080 for incoming requests.

Now let’s run the app with command: node server.js. Open your browser with url http://localhost:8080/, you will see:

node-js-express-sequelize-postgresql-example-setup-server

Yeah, the first step is done. We’re gonna work with Sequelize in the next section.

Configure PostgreSQL database & Sequelize

In the app folder, we create a separate config folder for configuration with db.config.js file like this:

First five parameters are for PostgreSQL connection. pool is optional, it will be used for Sequelize connection pool configuration:

  • max: maximum number of connection in pool

  • min: minimum number of connection in pool

  • idle: maximum time, in milliseconds, that a connection can be idle before being released

  • acquire: maximum time, in milliseconds, that pool will try to get connection before throwing error

For more details, please visit API Reference for the Sequelize constructor.

Initialize Sequelize

We’re gonna initialize Sequelize in app/models folder that will contain model in the next step.

Now create app/models/index.js with the following code:

Don’t forget to call sync() method in server.js:

In development, you may need to drop existing tables and re-sync database. Just use force: true as following code:

Define the Sequelize Model

In models folder, create tutorial.model.js file like this:

This Sequelize Model represents tutorials table in PostgreSQL database. These columns will be generated automatically: id, title, description, published, createdAt, updatedAt.

After initializing Sequelize, we don’t need to write CRUD functions, Sequelize supports all of them:

  • create a new Tutorial: create(object)

  • find a Tutorial by id: findByPk(id)

  • get all Tutorials: findAll()

  • update a Tutorial by id: update(data, where: { id: id })

  • remove a Tutorial: destroy(where: { id: id })

  • remove all Tutorials: destroy(where: {})

  • find all Tutorials by title: findAll({ where: { title: ... } })

These functions will be used in our Controller.

We can improve the example by adding Comments for each Tutorial. It is the One-to-Many Relationship and I write a tutorial for this at: Node.js Sequelize Associations: One-to-Many example

Or you can add Tags for each Tutorial and add Tutorials to Tag (Many-to-Many Relationship): Node.js Sequelize Associations: Many-to-Many example

Create the Controller

Inside app/controllers folder, let’s create tutorial.controller.js with these CRUD functions:

  • create

  • findAll

  • findOne

  • update

  • delete

  • deleteAll

  • findAllPublished

Let’s implement these functions.

Create a new object

Create and Save a new Tutorial:

Retrieve objects (with condition)

Retrieve all Tutorials/ find by title from the database:

We use req.query.title to get query string from the Request and consider it as condition for findAll() method.

Retrieve a single object

Find a single Tutorial with an id:

Update an object

Update a Tutorial identified by the id in the request:

Delete an object

Delete a Tutorial with the specified id:

Delete all objects

Delete all Tutorials from the database:

Find all objects by condition

Find all Tutorials with published = true:

Define Routes

When a client sends request for an endpoint using HTTP request (GET, POST, PUT, DELETE), we need to determine how the server will reponse by setting up the routes.

These are our routes:

  • /api/tutorials: GET, POST, DELETE

  • /api/tutorials/:id: GET, PUT, DELETE

  • /api/tutorials/published: GET

Create a turorial.routes.js inside app/routes folder with content like this:

You can see that we use a controller from /controllers/tutorial.controller.js.

We also need to include routes in server.js (right before app.listen()):

Test the APIs

Run our Node.js application with command: node server.js.

Using Postman, we’re gonna test all the Apis above.

  1. Create a new Tutorial using POST /tutorials Api

    node-js-express-sequelize-postgresql-crud-create

    After creating some new Tutorials, you can check PostgreSQL table:

  2. Retrieve all Tutorials using GET /tutorials Api

    node-js-express-sequelize-postgresql-crud-retrieve

  3. Retrieve a single Tutorial by id using GET /tutorials/:id Api

    node-js-express-sequelize-postgresql-crud-get-by-id

  4. Update a Tutorial using PUT /tutorials/:id Api

    node-js-express-sequelize-postgresql-crud-update

    Check tutorials table after some rows were updated:

  5. Find all Tutorials which title contains ‘js’: GET /tutorials?title=js

    node-js-express-sequelize-postgresql-crud-find-by-field

  6. Find all published Tutorials using GET /tutorials/published Api

    node-js-express-sequelize-postgresql-crud-find-published

  7. Delete a Tutorial using DELETE /tutorials/:id Api

    node-js-express-sequelize-postgresql-crud-delete

    Tutorial with id=4 was removed from tutorials table:

  8. Delete all Tutorials using DELETE /tutorials Api

    node-js-express-sequelize-postgresql-crud-delete-all

    Now there are no rows in tutorials table:

Last updated

Was this helpful?