,

Creating a REST API using Node.js (JavaScript), Express, and PostgreSQL

Posted by



Building a robust and efficient REST API is crucial for any modern application. It allows different systems and clients to communicate with each other seamlessly. In this article, we will explore how to build a REST API using NodeJS, Express, and PostgreSQL to handle database operations.

NodeJS, a powerful JavaScript runtime, provides an excellent platform for building scalable server-side applications. Express, a minimal and flexible NodeJS web application framework, simplifies the process of creating APIs. PostgreSQL, a highly advanced open-source relational database management system, offers robust features for storing and managing data.

To begin building our REST API, we first need to set up our development environment. Ensure that you have NodeJS and PostgreSQL installed on your machine. Once that is done, let’s dive into the implementation.

Step 1: Setting Up the Project
Create a new folder for your project and navigate to it using the command line. Initialize a new NodeJS project by running `npm init`. This will prompt you to enter details about your project and create a `package.json` file.

Step 2: Installing Dependencies
We need to install the necessary dependencies for our REST API. Run the following commands to install Express, PostgreSQL driver, and other required packages:
“`shell
npm install express pg pg-pool dotenv
“`

– `express` allows us to create routes and handle HTTP requests.
– `pg` is a NodeJS driver for PostgreSQL, allowing us to connect and interact with the database.
– `pg-pool` provides a connection pool for handling multiple database connections efficiently.
– `dotenv` allows us to use environment variables for configuration.

Step 3: Database Configuration
Create a `.env` file in your project’s root directory to store your environment variables. This helps in keeping sensitive information like database credentials secure. Add the following variables to the `.env` file:
“`
PGHOST=localhost
PGUSER=your_username
PGDATABASE=your_database
PGPASSWORD=your_password
PGPORT=5432
“`

Step 4: Setting Up the Server
Create an `index.js` file to set up our server and handle API endpoints. Import the required packages and initialize the Express application:
“`javascript
const express = require(‘express’);
const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
“`

Step 5: Connecting to the Database
Create a separate file called `db.js` to handle database operations. Import the `pg` package and configure the connection pool using the environment variables:
“`javascript
const { Pool } = require(‘pg’);

const pool = new Pool();

module.exports = {
query: (text, params) => pool.query(text, params),
};
“`

Step 6: Creating API Endpoints
In the `index.js` file, we can now create our API endpoints. Let’s create a basic endpoint to retrieve all users from the database:
“`javascript
const db = require(‘./db’);

app.get(‘/users’, async (req, res) => {
try {
const { rows } = await db.query(‘SELECT * FROM users’);
res.json(rows);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
“`

Step 7: Handling Post Requests
To handle POST requests, let’s create an endpoint to add a new user to the database:
“`javascript
app.post(‘/users’, async (req, res) => {
const { name, email } = req.body;

try {
const { rows } = await db.query(
‘INSERT INTO users (name, email) VALUES ($1, $2)’,
[name, email]
);
res.json(rows[0]);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
“`

Step 8: Testing the API
You can now start your server by running `node index.js` in the command line. Use an API testing tool like Postman or cURL to test your endpoints.

Conclusion
In this article, we have explored how to build a REST API using NodeJS, Express, and PostgreSQL. We covered setting up the project, installing dependencies, configuring the database connection, creating API endpoints, and handling HTTP requests. With these tools and techniques, you can build powerful and scalable REST APIs to support your applications.

0 0 votes
Article Rating
20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
RockstahRolln
8 months ago

Phenomenal Tutorial, precisely what I was looking for!! Going to re-watch it entirely again and work through it! Brilliant!!

Debbie Tampa she her
8 months ago

So easy to follow and so helpful

Nur E Alam Jony
8 months ago

Simple and Simple

Narayana Aaditya
8 months ago

Awesome tutorial!!

Healthy Body, Healthy Life💚
8 months ago

bro. thank you very much for this amazing tutorial.

Lucas Campos
8 months ago

Very Good!! Thanks

Umesh Kumar
8 months ago

Can you mention the VS code theme that you have used? I liked it very much.

Namespace_Manny
8 months ago

This video saved me so much time. It got me up and running so quickly. Thank you for this!

Saheed Shittu
8 months ago

Repo link?

Juan Montes
8 months ago

This was a really informative video, easy to follow, I bumped into some errors that it got easily fixed with just restarting the server, now I understand why you have to create errorHandlers and all that stuff so everything works the way it's supposed to without anything crashing🤓☝

Temtechie
8 months ago

Great folder structure

Phillip Hess
8 months ago

dude i'm rehashing my knowledge on psql and express, this video helped out perfectly. front to back thank you , excellent tutorial.

Mohammad Malek
8 months ago

very good
thanks

Ap?
Ap?
8 months ago

Great tutorial sir <3 but is there a way to use already created database

Noel Hdez
8 months ago

nice vid!

JOSÉ Jaimes
8 months ago

Hi Austin,
Your tutorial is wonderful. It is really easy to understand.

Do you have the deployment process in a Server different to Heroku and Azure?

Thanks a lot.

Nirvana
8 months ago

best tut i saw on this topic, everything is very well maintained and scructured

Todd H
8 months ago

First week of my DB course in CS and this is exactly what I needed to understand how to connect postgreSQL and my express server. Thank you for a great video!

Michel Mongeau
8 months ago

Best tutorial on the topic… and like most folks, I probably watched too many to count!
Well done @AustinBeaufort !

In your 'removeStudent' function, I notice the delete query is outside of a conditional statement and looks as though it will execute regardless of the noStudentFound value. Is that correct or should the delete query be inside an }else{ section?

John del Mar
8 months ago

Great video, very cool.