Last updated on September 6th, 2024 at 07:05 pm
Build a RESTful API with Node.JS ,Express and PostgreSQL(driver)
Last updated on September 6th, 2024 at 07:05 pm
REST API’s are like Swiss army knife that can be so handy and useful and seem to never go out of fashion.They are tiny and nimble and yet still pack enough punch like their big brothers do. And just like the Swiss army knife you can build them with so many different combinations ( different programming languages , frameworks, databases , ORM’s,ODM’s, and so on)
In this tutorial we are going to explore the process of building a REST API with Node.JS, Express and PostgreSQL, using Node.js driver for Postgresql called pg
. By the End of this tutorial you will be able to create api endpoints that can be integrated into any frontend application and communicate with the Postgres database like a boss. You will have created separate endpoints to create, retrieve , update and delete data. In our example we will build api for note taking app.
So hold tight, the ride is about to begin.
Prerequisites:
- Node.js & npm installed.
- postGreSQL database (local)
- Code editor /IDE ( we are using VS Code ).
- Postman – A popular API testing Client or Thunder Client- A VS Code extension for API testing
- *pgAdmin(GUI for postgreSQL) or SQLTools- a VSCode extension that can work as GUI for SQL based databases- *optional
- An ounce of Curiosity & Pint of Patience.
Warm-up: Getting familiar with techStack & keywords:
- Node.JS: A JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Its is just the same old JavaScript but now you can run it on your machine outside the browser.In our case we are using it to build a server that will handle our API requests.
- Express: A minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It is widely used in node.js applications to build api’s and middleware functions.
- PostGreSQL: According to official documentaion “PostgreSQL is a powerful, open source object-relational database system”. It supports both relational (SQL) and non-relational (JSON) queries.In our example we will be using SQL queries on the database hosted locally.(for simplicity we we will refer to it as postgres db through out the article)
- REST API: REST stands for Representational State Transfer. It is a standard for designing web based system where data is transferred between applications. API stands for Application programming interface . In a REST API, this interface allows data transfer via methods like POST,GET,PUT & DELETE defined by REST protocol.
- CRUD : CRUD stands for Create, Read, Update, and Delete. These are the basic operations that can be performed on data. We will implement these operations in our API.
- Postman: A popular API testing tool that allows you to test your APIs by sending HTTP requests and inspecting the responses. We will use Postman desktop application for mac to test our API.
- Thunder Client: A lightweight Rest API Client Extension for VS Code. You can test your API’s within your IDE so ease your workflow
- SQL Tools(VS Code Extension): A VSCode extension that really simplifies working with databases. Easily write and execute SQL queries and visualize the table results, directly in your favorite IDE. Easily establish connection with your database of choice.
Brief overview of the project:
We will build an API with following routes.
Method | Endpoints | Description |
POST | /notes | Creates a new Note |
GET | /notes | Fetches all Notes |
GET | /notes/:id | Fetches single note by Id |
PUT | /notes/:id | Updates existing note(by id) |
DELETE | /notes/:id | Deletes single note |
DELETE | /notes | Deletes all notes in the table |
To store these data we will create a table in postgres DB . We will write functions/methods with the SQL queries which gets executed in the database. To create the communication channel with the database we will first establish a connection( with locally hosted postgres db). We will run our server locally on our machine in one of the available(defined) ports where the node application can run and serve the results of our query.
The project will be divided into separate module based on tasks they facilitate. We will be following MVC pattern and hence will factor our code in following separate modules/ directories : models, controllers and routes. At the end we will test the api’s using postman/ thunder client. We can also test it using our own frontend Notes application built with React/NextJS.
Setting up the project:
- To setup a node project we use CLI(Command Line Interface ) with npm (Node Package Manager)
- Create a new directory for your project and navigate into it.
- Run npm init to initiate a new Node.js project.
- Install the required dependencies from npm:
- express: A web application framework for Node.js
- pg: postgres driver for Node.js
- dotenv: A zero-dependency module that loads environment variables from a .env file into process.env. This helps us to securely store our database connection info
- nodemon(optional): A utility that will monitor for any changes in your source and automatically restart your server. This is useful during development. It automatically restarts the server when you make changes to your code and hence saves you the time of manually restarting the server.
- cors(optional): A package that allows you to enable CORS with various options. This is needed if you want to make requests to your API from a different domain. We will need this when our react/nextjs frontend hosted on different domain makes requests to our API.
- MVC: It stands for Model-View-Controller. It is a software design pattern that divides the application into three interconnected components. This separation helps to organize the code and make it easier to maintain and scale.
mkdir <project_name> && cd <project_name>
npm init --y
// here --y flag will answer yes to all questions by default that are asked during project initiation, this can be changed later in package.json file
npm install express pg dotenv nodemon
//Installing all the dependencies/libraries used in this project
- Create a .env file in the root of your project and add the following environment variables as such.
HOST="localhost"
USERDB="<YOUR DB USERNAME>"
PASSWORD="<YOUR DB PASSWORD>"
DB="<YOUR DB NAME>"
- Create an entryway file for your application(server.js) in the root of your project and set up your server.
Setting up the server:
- In server.js, we will first import the required dependecies.
- Next, we will set up the Express app.
- We will then define an initial/default route for testing. This route will return a message on the browswer when the server is running.
- Finally we define a PORT variable and listen for requests on that port. We will log a message to the console when the server is running.
//server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 4000;
app.get("/", (req, res) => {
res.json({ message: "Welcome notes app with postGreSQL." });
})
app.listen(PORT, () => {
console.log(`Server is currently running on port:${PORT} go to http://localhost:${PORT}`)
})
- We can now start the server by running `nodemon server.js` in the terminal.(note: you can opt for `node server.js` but you will have to manually restart the server everytime you make changes to your code)
Now if we go to your browser and navigate to http://localhost:4000, you should see the message “Welcome to the notes app with postgreSQL” displayed on the screen.