Building a RESTful API with Express, PostgreSQL, and Node Using ES6

By Sanni Kehinde, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud’s incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

In this guide, I would be explaining how to build a basic bookstore RESTful API where a user can perform a basic CRUD (CREATE, READ, UPDATE AND DELETE) operation.

Tools

Below are the tools and technologies we would be using for building our RESTful API

  1. NodeJS — Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser. Basically, we would be using this to run our javascript code on the server.
  2. Express — This is a web application framework for Node.js which we would be using as a server for our API’s.
  3. PostgreSQL — This is an open source object-relational database system which we would be using to save our bookstore content.
  4. Sequelize — This is an ORM (Object Relational Mapper) for communicating with our PostgreSQL database.
  5. Postman — A Chrome app that we’ll use to practically test our API.
  6. ES6 — ES6, officially known as ECMAScript 2015, is a scripting-language specification standardized created to standardize JavaScript.

Prerequisites

This guide assumes the following

  1. You already have a basic knowledge of JavaScript
  2. you have PostgreSQL database and NodeJS installed on your machine.

If you don’t have it set up, read this tutorial to set up PostgreSQL on an Alibaba Cloud Elastic Compute Service (ECS) instance.

What’s RESTful API?

A RESTful API also referred to as RESTful web service and is based on representational state transfer(REST) technology, an architectural style and approach to communications often used in web services development. It’s an application program interface (API) that uses HTTP requests such as GET, PUT, POST and DELETE methods on data.

While most API’s claim to be RESTful, it’s important to know that there are some conditions that determine if your API is RESTful which are listed below

  • Client-Server-based
  • Stateless operations
  • RESTful resource caching
  • Use of a uniform interface.

Check on this link for more explanation on RESTful API conditions.

Getting Started

  1. To get started with building our RESTful API, we need to create a directory for our project. Move into the new directory and initialize NodeJS by running the command below
  1. This would create a file in our root directory.
  2. Most browsers currently doesn’t support ES6, so we are going to make use of babel to transpile our code from ES6 to ES5 so as to run on our browser.
  3. run the command below to set up babel
  1. run to create a babel configuration file. and paste the code below
  1. Creating our express application
  2. With babel setup, we can now create our RESTful API using ES6. To create our express application, we need to install express alongside some dependencies
  1. Create a new file named to setup express
  1. and paste the code below
  1. We need to install to restart our server whenever we make changes to any of our file.
  1. To use , open the file and update the scripts section to the code below
  1. We are using nodemon to run the application and to transpile our application from to on the run.
  2. Now we can run our application with command.
  3. Setup sequelize
  4. With our application up and running, we need to install the sequelize library to connect to our postgreSQL database.
  5. Install Sequelize, (for making the database connection) and (for serializing and deserializing JSON into the Postgres hstore key/value pair format):
  1. We need to install the which enable us to run database migration easily from the terminal and bootstrap a new project.
  1. Next, we are going to create a config file in our root directory for sequelize named . Basically, In this file, we are telling sequelize where to find to it's required files.
  1. and paste the code below
  1. This sequelize configuration file is explain below
  • Config: This file contains our application configuration settings such as database configuration.
  • Models: This is where we save our database models
  • Seeders: This folder saves our application seed data. Seed data are mock data used for testing or templating purpose.
  • Migrations: This folder would hold our application migration data
  1. To create the files specified in the file, we are going to initialize sequelize by running .
  1. After running command, Here is the structure of the files generated
  1. Let take a look at the file generated in the directory
  1. So in this file, we establish a connection to the database, grab all the model files from the current directory, add them to the db object, and apply any relations between each model (if any). This file uses environment by default if is not specified.
  2. We need to create our bookstore database. Run the command below to create a new database
  1. command would be available once you have postgreSQL installed on your machine.
  2. For the file in the directory, edit the file to fit the code below
  1. For the purpose of this tutorial, we are only going to be using the development environment.
  2. Models
  3. Now, we are going to create the models for our bookstore application and define the associations. Below is the schema for our bookstore. A schema is just a blueprint of how our database is being structured.
  1. User model
  2. To create our user model, run the command below
  1. A new user migration file would be created in the directory as shown below
  1. When we run our migration, which we are going to do later in this section, the function would be executed and creates the table and associated columns for us in our database. whenever we want to undo such changes the function would be executed when we run the command.
  2. Let take a lot at the user model file generated in the directory
  1. We also need to update our user migration file to include the changes we made to our user model file.
  2. Open the user migration file at and update it to read the code below
  1. Book model
  2. To create our user model, run the command below
  1. A book model file is generated in the directory as shown below
  1. We would also update this file to use and add some validations for our book model
  1. We are also going to update the migration file at to include the changes made to the book model.
  1. Association
  2. Now, we need to define the associations between our and model. As a user, I should be able to have as books as possible while a book should a particular user. So our user model is going to have a relationship with the book model while our book model would have a relationship with the user model. You can check on the for more explanation on associations.
  3. Edit the file in the directory to define the relationship between and as shown below
  1. The ensures whenever we delete a user, the associated with such user should also be deleted.
  2. With the models and migrations in place, we can create those changes to the database by running the command below
  1. Controllers
  2. With our models and database in place, we are ready to create our controllers. We would be creating a and controllers, The controllers would be responsible for the operations

For our user controller

  1. Create a folder in the directory
  2. create a file in the directory to define our user functionality which would also a user to create an account.
  1. Basically, we are importing our models object and then use to get our user model. In our class, we create a method called which is responsible for creating our user.
  2. Create a folder in the directory
  3. Create an file in the directory. This is where we are going to define our API endpoints. Paste the code below
  1. In this file, we are importing our class and defining two API endpoints.
  2. The first endpoint which is the endpoint has an HTTP Method of which can be translated as in the CRUD operation.
  3. his second endpoint which is the endpoint has an HTTP Method of which can be translated as in the CRUD operation. Whenever we hit this API endpoint, we are calling the method from our class which is going to create a new user.
  4. We need to make our application aware of the route file we just created. Open the file and edit it to look like this
  1. To test our API endpoint, Open up and create a new user as shown below
  1. Note when building either a production or development ready API, you are to encrypt the value using packages like bcrypt. You should see the user data you created just now in your database.

For our book controller

  1. Creating a book
  2. We would be creating a controller to allow a user to create a new book. To do that, follow the steps below
  3. create a new file named in the directory and paste the code below
  1. We need to create an API endpoint for creating a book. To do so, Open the file in the directory and update the code to read this
  1. Note that is the Id of user we created earlier
  2. Open up Postman to test the API endpoint for creating a book. as shown below
  1. Listing all books
  2. We would modify our book controller to enable us to get the list of all the books in our database
  3. Open in the directory and update it to include this
  1. Update the file in the directory to define our API for listing all books.
  1. Open up postman and test the new route
  1. Updating a book
  2. We would modify our book controller to allow us to modify a book data in our database
  3. Open in the directory and update it to include this
  1. Update the file in the directory to define our API endpoint for editing a books.
  1. is the id of the book to be edited
  2. Open up postman and test the new route
  1. Deleting a book
  2. Finally, we are going to add a functionality to delete a book
  3. Open in the directory and update it to include this
  1. Update the file in the directory to define our API endpoint for editing a books.
  1. Open up postman and test the new route
  1. For reference purposes, The complete code for this article can be found on this Github Repository

Conclusion

Finally, we have come to the end of this article. This article is just a basic of getting started with RESTful API. We were able to create a basic CRUD operation, but here are some few things you could try out on your own

  1. Encrypt the password field using packages like bcrypt
  2. Create an API endpoint for getting just a book
  3. Complete the authorization feature. we only have an endpoint for a user to sign up, you can create an endpoint for sign in and authorize using packages like passport or JWT(JsonWebToken)
  4. You could also improve on the validations.

Reference:https://www.alibabacloud.com/blog/building-a-restful-api-with-express%2C-postgresql%2C-and-node-using-es6_594137?spm=a2c41.12245160.0.0

Follow me to keep abreast with the latest technology news, industry insights, and developer trends.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store