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.
What is a CRUD?
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.
Create: 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.
Read: 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.
Update: 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.
Delete: 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.
What is REST API?
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.
What is Express.js?
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 javascript development company 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.
What is PostgreSQL?
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.
Step-by-step guide
The procedure is outlined below.
Create a new file folder
mkdir node-crud-api
Get into it.
cd node-crud-api
Launch a brand new npm project.
npminit -y
install the dependencies
npm i express pgsequelize
- The express framework for Node.js
- The pg driver establishes a connection to a Postgres database.
- Instead of manually entering SQL queries, we may use sequelize, an object-relational mapper.
Make 4 Separate Files
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:
code.
You should now have a file with the following structure:
It's time to begin writing code.
Database connection
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.
Fill up the database file at util/database.js.
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;
User model
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 Nodejs development company.
Make entries in models/user.js:
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;
Controllers
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');
// CRUD Controllers
//get all users
exports.getUsers = (req, res, next) => {
User.findAll()
.then(users => {
res.status(200).json({ users: users });
})
.catch(err => console.log(err));
}
//get user by id
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));
}
//create user
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);
});
}
//update user,
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));
}
//delete user
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));
}
Routes
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;
Index file
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();
});
//test route
app.get('/', (req, res, next) => {
res.send('Hello World');
});
//CRUD routes
app.use('/users', require('./routes/users'));
//error handling
app.use((error, req, res, next) => {
console.log(error);
const status = error.statusCode || 500;
const message = error.message;
res.status(status).json({ message: message });
});
//sync database
sequelize
.sync()
.then(result => {
console.log("Database connected");
app.listen(3000);
})
.catch(err => console.log(err));
Docker Part
Let's make three additional primary folder files:
- docker ignore (it starts with a dot)
- Dockerfile (capital D)
- docker-compose.yml
This is how the framework has to be set up:
There will be a solitary line in the. Docker ignores the file, which reads:
node_modules
The Dockerfile
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.
FROM node:14
# Create app directory
WORKDIR /app
COPY package*.json ./
RUN npm install
# Bundle app source
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: {}
Create a Docker image, then launch the containers within it.
Use a container to manage PostgreSQL.
Launching the Postgres container comes first:
docker compose up -d node_db
Type: to access the logs.
docker compose logs
Ideally, you'd see a result like this:
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.
Just copy the settings from the docker-compose.yml file. If you've kept the default settings, the password is 12345.
Create a Docker environment and launch the service.
The second step is to create our Docker image.
We may now begin the service.
docker compose up node_app
The terminal should show this as the output.
Put Postman to the app's test.
Let me use Postman to test the app.
Ping localhost:3000 with a GET request.
Ping localhost:3000/users with a GET request.
We expect an empty array as a reply.
We'll be making three users: aaa, bbb, and ccc.
Let's double-check all of the users again:
Ping localhost:3000/users with a GET request.
There should be three visitors:
Start with one person, say, user 2.
Try sending a GET request to localhost:3000/users/2.
Here we will modify an existing user, say user 2.
Try sending a PUT request to localhost:3000/users/2 with a new body.
Now that we're done let's eliminate user #3.
Start by sending a DELETE request to localhost:3000/users/3.
In addition, we may useTablePlus to verify the results.
Conclusion
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.
Top comments (2)
Thank you for your kind words. What out for more amazing contents!
Thank you for sharing!
Useful content about CRUD API with JavaScript. It will helps me in knowing CRUD API more! Thanks for sharing.