You Can Build a Crud Api in Javascript with the Help of Node.js, Express, Postgres, and Docker
Tags: restapi, javascript, docker
Published: 2023-02-23 09:06:22

---
title: You Can Build a Crud Api in Javascript with the Help of Node.js, Express, Postgres, and Docker
published: true
description: Developers may follow this project's detailed instructions to set up a CRUD REST API in Docker, utilizing tools like Node.js, Express, Postgres, and why use angular in 2023.
tags: #RESTAPI #Javascript #Docker
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-02-23 06:45 +0000
---
<img src="https://miro.medium.com/max/1008/1*_qjUgj_wgzKs6gdH49i4Lg.png">
To make websites, you must be familiar with application programming interfaces (APIs), which facilitate communication between software systems. Here you will learn how to create a CRUD REST API in Node.js with the help of the Express.js server and the PostgreSQL database. This article will discuss the node-postgres package and how it may link an Express.js server to PostgreSQL.

The API will be compatible with HTTP request methods that are standard in the PostgreSQL database. The installation of PostgreSQLand its command line interface will also be covered.

This article aims to allow CRUD activities (GET, POST, PUT, and DELETE) on the API so that you may run queries on the database. To get the data, we must build a route to each endpoint and a query function.

<h2></b>What is a CRUD?</b></h2>

Create, Read, Update, and Delete (CRUD) is an abbreviation for the four operations. It's a collection of procedures for working with data in a database, and it's widely used in DBA tools and web apps. Moreover to know how the CURD benefits and why use angular in 2023 you should hire Angular development services.

<b>Create:</b> Making new database entries is what this process is all about. For instance, when a user opens an account on a website, that person's details are recorded in a database.

<b>Read:</b> Data is fetched or read from a database in this process. For instance, a website verifies a user's identification by retrieving their details from a database each time they log in.

<b>Update:</b> Changing or altering preexisting information in a database constitutes this activity. For example, when a person edits their profile information on a website, that information is updated in the backend database.

<b>Delete:</b> Doing this action means wiping out information from a database. If a person deletes their account, that individual's data will also be removed from the website's database.

<h2></b>What is REST API?</b></h2>

Representational State Transfer, or REST for short, is an architectural style that defines a set of restrictions that web services may use to interact. A RESTful API (Application Programming Interface) adheres to these guidelines and uses the HTTP protocol so that clients may access and modify resources on a server.

A REST API is a set of guidelines for developing web services that facilitate online communication between programs. It enables adaptable, scalable, and standard interoperability across disparate systems. Often employed in today's online development, REST APIs are the backbone upon which several successful websites, apps, and services have been constructed.

<h2></b>What is Express.js?</b></h2>

Express.js is a well-liked Node.js web framework. Although it offers a bare-bones feature set for creating Node.js web apps and APIs, its middleware framework allows developers to add more advanced capabilities. A professional <a href="https://www.cmarix.com/javascript-development.html"><b>javascript development company</b></a> can help you leverage the potential of Express.js.

Express.js is a web application framework that is both lightweight and adaptable, allowing for individualized development. It has inbuilt support for dealing with data formats like JSON and XML and managing HTTP requests and answers. Hire Angular Developers who use Express.js all around the globe because it allows them to create websites and APIs that are quick to load, scalable, and reliable.

<h2></b>What is PostgreSQL?</b></h2>

PostgreSQL is a free and open-source RDBMS emphasizing these qualities and being resilient and compliant with the SQL standard. Originating at UC Berkeley, it is today supported by programmers worldwide. 

Tables containing rows and columns are used to organize data in PostgreSQL, which is stored in databases. It's capable of handling a variety of data formats and has sophisticated features, including transactions, foreign keys, triggers, and stored procedures. 

PostgreSQL's reputation for dependability and durability has led to its widespread adoption in enterprise-level applications requiring high throughput and constant accessibility. It's open source, supports several platforms, and has a generous license.

<b>Step-by-step guide</b>

The procedure is outlined below.

Create a new file folder

<b>mkdir node-crud-api</b>

Get into it.

<b>cd node-crud-api</b>

Launch a brand new npm project.

<b>npminit -y</b>

install the dependencies

<b>npm i express pgsequelize</b>

<ul><li>The express framework for Node.js</li>

<li>The pg driver establishes a connection to a Postgres database.</li>

<li>Instead of manually entering SQL queries, we may use sequelize, an object-relational mapper.</li></ul>

<b>Make 4 Separate Files</b>

mkdir controllers routes util models

Launch the integrated development environment you like and open the folder. To use Visual Studio Code in the terminal, enter the following:

<b>code.</b>

You should now have a file with the following structure:
<img src="https://i.ibb.co/TYWvL2x/1.png">

It's time to begin writing code.

<b>Database connection</b>

Create a database.js document in the "util" folder.

The file's contents will provide the settings necessary for the Node.js application to communicate with the currently active Postgres server.

<b>Fill up the database file at util/database.js.</b>
constSequelize = require('sequelize');

constsequelize = new Sequelize(
process.env.PG_DB,
process.env.PG_USER,
process.env.PG_PASSWORD,
    {
host: process.env.PG_HOST,
dialect: 'postgres',
    }
);

module.exports = sequelize;

<b>User model</b>

Create a brand new file called "user.js" under the "models" folder.

Here you'll find the model, in this example, a user profile complete with auto-incremented id, name, and email address. It becomes easy to create this user model by hiring an expert <a href="https://www.cmarix.com/node-js-development.html"><b>Nodejs development company</b></a>.

Make entries in models/user.js:

<b>constSequelize = require('sequelize');
constdb = require('../util/database');

const User = db.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
    },
name: Sequelize.STRING,
email: Sequelize.STRING
});
module.exports = User;</b>

<b>Controllers</b>


Make a brand new file called "user.js" and place it within the "models" folder.

Here you'll find the model, in this example, a user profile complete with auto-incremented id, name, and email address.
Make entries in models/user.js:

const User = require('../models/user');

<b>// CRUD Controllers</b>


<b>//get all users</b>
exports.getUsers = (req, res, next) => {
User.findAll()
        .then(users => {
res.status(200).json({ users: users });
        })
        .catch(err => console.log(err));
}

<b>//get user by id</b>
exports.getUser = (req, res, next) => {
constuserId = req.params.userId;
User.findByPk(userId)
        .then(user => {
if (!user) {
returnres.status(404).json({ message: 'User not found!' });
            }
res.status(200).json({ user: user });
        })
        .catch(err => console.log(err));
}

<b>//create user</b>
exports.createUser = (req, res, next) => {
const name = req.body.name;
const email = req.body.email;
User.create({
name: name,
email: email
  })
    .then(result => {
console.log('Created User');
res.status(201).json({
message: 'User created successfully!',
user: result
      });
    })
    .catch(err => {
console.log(err);
    }); 
}

<b>//update user,</b>
exports.updateUser = (req, res, next) => {
constuserId = req.params.userId;
constupdatedName = req.body.name;
constupdatedEmail = req.body.email;
User.findByPk(userId)
    .then(user => {
if (!user) {
returnres.status(404).json({ message: 'User not found!' });
      }
      user.name = updatedName;
user.email = updatedEmail;
returnuser.save();
    })
    .then(result => {
res.status(200).json({message: 'User updated!', user: result});
    })
    .catch(err => console.log(err));
}

<b>//delete user</b>
exports.deleteUser = (req, res, next) => {
constuserId = req.params.userId;
User.findByPk(userId)
    .then(user => {
if (!user) {
returnres.status(404).json({ message: 'User not found!' });
      }
returnUser.destroy({
where: {
id: userId
        }
      });
    })
    .then(result => {
res.status(200).json({ message: 'User deleted!' });
    })
    .catch(err => console.log(err));
}

<b>Routes</b>

The "users.js" file should be in the "routes" folder.

Add users to the routes/users.js file.

const controller = require('../controllers/users');
const router = require('express').Router();

// CRUD Routes /users
router.get('/', controller.getUsers); // /users
router.get('/:userId', controller.getUser); // /users/:userId
router.post('/', controller.createUser); // /users
router.put('/:userId', controller.updateUser); // /users/:userId
router.delete('/:userId', controller.deleteUser); // /users/:userId

module.exports = router;

</b>Index file</b>

Our program requires an additional file to be created in the /root directory.The contents of this file will be run within the docker container.

Create a new file named index.js in the primary folder.

Indicate in the "index.js file":

const express = require('express');
constbodyparser = require('body-parser');
constsequelize = require('./util/database');

const User = require('./models/user');

const app = express();

app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));

app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
next();
});

<b>//test route</b>
app.get('/', (req, res, next) => {
res.send('Hello World');
});

<b>//CRUD routes</b>
app.use('/users', require('./routes/users'));

<b>//error handling</b>
app.use((error, req, res, next) => {
console.log(error);
const status = error.statusCode || 500;
const message = error.message;
res.status(status).json({ message: message });
});

<b>//sync database</b>
sequelize
  .sync()
  .then(result => {
console.log("Database connected");
app.listen(3000);
  })
  .catch(err => console.log(err));

<b>Docker Part</b>

Let's make three additional primary folder files:

<ul><li>docker ignore (it starts with a dot)<li>
<li>Dockerfile (capital D)<li>
<li>docker-compose.yml<li></ul>

This is how the framework has to be set up:

<img src="https://i.ibb.co/TYWvL2x/1.png">

There will be a solitary line in the. Docker ignores the file, which reads:
node_modules

<img src="https://i.ibb.co/sj2csxK/3.png">

<b>The Dockerfile</b>

An easy-to-use but potent file is required for creating a Docker image. Dockerfile is the term for it (capital D). Let's keep things essential for now, even if we're considering a name change.

<b>FROM node:14</b>

<b># Create app directory</b>
WORKDIR /app

COPY package*.json ./
RUN npm install
<b># Bundle app source</b>
COPY . .
EXPOSE 3000
CMD [ "node", "index.js" ]
Docker compose file

A simple method to maintain multiple active services is to create a file named "docker-compose.yml."

The file called docker-compose.yml:


version: "3.9"
services:
node_app:
container_name: node_app
build: .
image: francescoxx/node_live_app
ports:
      - "3000:3000"
environment:
      - PG_DB=node_live_db
      - PG_USER=francesco
      - PG_PASSWORD=12345
      - PG_HOST=node_db
depends_on:
      - node_db

node_db:
container_name: node_db
image: postgres:12
ports:
      - "5432:5432"
environment:
      - POSTGRES_DB=node_live_db
      - POSTGRES_USER=francesco
      - POSTGRES_PASSWORD=12345
volumes:
      - node_db_data:/var/lib/postgresql/data

volumes:
node_db_data: {}

<b>Create a Docker image, then launch the containers within it.</b>

Use a container to manage PostgreSQL.
Launching the Postgres container comes first:

</b>docker compose up -d node_db</b>

Type: to access the logs.

<b>docker compose logs</b>

Ideally, you'd see a result like this:

<img src="https://i.ibb.co/8Md5Rt2/4.png">

We can proceed if the message "database system is ready to accept connections" appears.

Use TablePlus to see whether it works.
A new link may be made by selecting the plus sign.

<img src="https://i.ibb.co/MsCgwcW/5.png">

Just copy the settings from the docker-compose.yml file. If you've kept the default settings, the password is 12345.

<img src="https://i.ibb.co/3WtnTy1/6.png">
<b>Create a Docker environment and launch the service.</b>

The second step is to create our Docker image.

<b>docker compose build</b>
<img src="https://i.ibb.co/yXGmjfk/7.png">

We may now begin the service.

</b>docker compose up node_app<b>

The terminal should show this as the output.
<img src="https://i.ibb.co/3Md4Pjg/8.png">
<b>Put Postman to the app's test.</b>

Let me use Postman to test the app.

<b>Ping localhost:3000 with a GET request.</b>
<img src="https://i.ibb.co/fHf3QFy/9.png">
<b>Ping localhost:3000/users with a GET request.</b>

<b>We expect an empty array as a reply.</b>

<img src="https://i.ibb.co/yhWtmMZ/10.png">

We'll be making three users: aaa, bbb, and ccc.

<img src="https://i.ibb.co/b6VFN3v/11.png">

<img src="https://i.ibb.co/4f7GP4V/12.png">

<img src="https://i.ibb.co/52JmSd8/13.png">

Let's double-check all of the users again:

Ping localhost:3000/users with a GET request.

There should be three visitors:

<img src="https://i.ibb.co/52JmSd8/13.png">

Start with one person, say, user 2.

Try sending a GET request to localhost:3000/users/2.
<img src="https://i.ibb.co/xH5ydfk/15.png">

Here we will modify an existing user, say user 2.

Try sending a PUT request to localhost:3000/users/2 with a new body.

<img src="https://i.ibb.co/Sn1D0GP/16.png">

Now that we're done let's eliminate user #3.

Start by sending a DELETE request to localhost:3000/users/3.
<img src="https://i.ibb.co/58zKxXL/17.png">

In addition, we may useTablePlus to verify the results.
<img src="https://i.ibb.co/m8VmzMc/18.png">

<h3></b>Conclusion</b></h3>

Developers may follow this project's detailed instructions to set up a CRUD REST API in Docker, utilizing tools like Node.js, Express, Postgres, and why use angular in 2023. This guide will help developers understand how to implement CRUD APIs and related technologies into their own software development efforts.