Building REST APIS Using NODE And EXPRESS With POSTGRESQL

 

pg1

Hi Folks,

why to learn nodejs? why open source?What is node js?What is express? How to build rest apis in node using express? we will learn this questions in this blog.

why to learn nodejs ?

Because nodejs is easy and simple and open source and cross platform and single threaded and fast performance. It makes developer life easier because both frontend and backend can be done in same language and easier to maintain the naming conventions between server and client side. javascript is most popular language in present.

Why open source ?

In this modern most of the softwares are coming as open source in which developer gets the flexibility to change the source code to make a function to behave differently and add new features to existing software .

What is nodejs?

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.

What is express?

Express. js is a web application framework for Node. js. It provides various features that make web application development fast and easy which otherwise takes more time using only Node.

How to Build rest apis in node using express?

So lets go and start creating rest apis in node using express step by step.

Pre requisites for this course:

work experience with JavaScript and any SQL database experience.

Nodejs : https://nodejs.org/en/download/

Install node js based on your machine specifications and install it by selecting all default selections.

Once Node is installed to verify node open cmd and enter command "node -v"

You will get the node version. if you are not getting node is not installed properly. if not installed properly uninstall and follow some youtube video to install nodejs and install it.

v14.17.0 my node version.

if node shows the version. the enter command "npm -v" 

6.14.13 my npm version

This command will show you npm version npm stands for node package manager. this is important to install the node dependencies.

Visual Studio Code: https://code.visualstudio.com/download

Go to above website and install the visual studio code based on your PC configurations. we are using visual studio code as a editor for this tutorial it is free and open source.

PostgreSQL: https://www.postgresql.org/download/

We are using PostgreSQL as a database for this course. It is also open source and once it is installed it will work as client server model. While installing it will create a user with admin permissions named as "postgres" and asks for password. Please enter the password and save this password for future use.

Postman: https://www.postman.com/downloads/

In this tutorial we are building REST APIs . To test the APIs we will use postman.

with no late we will start writing code to create APIs.

1. Creating Basic Express Application.
2. Create Task Table in PostgreSQL
3. Creating Data Layer
4. Creating Routes and Task Routes
5. Running and Testing in POSTMAN


1. Creating Basic Express Application.

Step 1:

create new folder in file explorer and open that folder in visual studio code by selecting below option.

pg2

Step 2: 

after opening you folder the folder name will be shown in explorer as shown below then open Terminal and New Terminal as shown below.

pg3

pg3

Step 3:

 Here will install all required dependencies for the project using below command. run command "npm init" in new terminal the it will ask project name and different option select based on your interest . This command will create package.json file in the folder.

pg4

I have selected as above.

open package.json file: that will be shown up like this. 

name: project name

version: version of the project

description: description of the project

main: this is the entry point of the application.

scripts: here we can define different commands for development prod staging and testing.

author: name of the author

license: if available default value is "ISC".

pg5

Install express:

go to terminal again and install express by below command

npm install express

pg5
This command will create modules folder and all dependencies for the express.
pg6


 Install pg:

go to terminal again and install pg by below command.pg is used to connect to postgresql database.

npm install pg

sp3



Run web server using express on a PORT:

To do this create new file name called index,js and paste below code.

index.js

const expressrequire('express');
const appexpress();
const PORT=3002;

app.listen(PORT,()=>{
    console.log('Started web server at port'+PORT);
})

app.get('/',(req,res)=>{
    res.json('Hello world');
});

pg10



in Terminal run the node application using command: "node index"
after open web browser and open new tab and open "http://localhost:3002/"

pg7


2. Create Task Table in PostgreSQL:

 Open PostgreSQL windows start->SQL Shell
pg11
after opening select everything default and enter password what you have given at the time of installation.
pg13

Create Table Script: Execute table script in sql shell it will create table in DB

-- Table: public.task

-- DROP TABLE public.task;


CREATE TABLE public.task
(
    id bigint NOT NULL,
    task_name character varying(100) COLLATE pg_catalog."default",
    description character varying(200) COLLATE pg_catalog."default",
    status character varying(100) COLLATE pg_catalog."default",
    completed_date date,
    created_date date,
    CONSTRAINT task_pkey PRIMARY KEY (id)
)

TABLESPACE pg_default;

ALTER TABLE public.task
    OWNER to postgres;

After execution of create table check select table and confirm table is created successfully.
fd1


Db Connection file create new folder called database and in that create a file names pgsql and paste the below code.

database/pgsql.js


const pgrequire('pg');
const PGUser'postgres';
const PGDatabase='DevEnvironment';
const PGServer='localhost';
const PGPassword='password';

const config={
    server:PGServer,
    user:PGUser,
    password:PGPassword,
    database:PGDatabase
}

const pool = new pg.Pool(config);

module.exports=pool;

sp1


3.Creating DataLayer:


Create Datalayer folder and add file named taskDAL as below and add this code.

Datalayer/taskDAL.js


const dbrequire('../database/pgsql')

const gettask=async (req,res)=>{
    try{
        let dbresult=await db.query("select * from task");
        res.json(dbresult.rows);
    }
    catch(err){
        console.error(err);
    }
}

const posttask=async (req,res)=>{
    try{
        let dbquery=`INSERT INTO public.task(
            id, task_name, description, status, completed_date, created_date)
            VALUES (${req.body.id},'${req.body.task_name}','${req.body.description}','${req.body.status}','${req.body.completed_date}'
            ,'${req.body.created_date}')`;
          let dbresult=await db.query(dbquery);
          res.json(req.body);
    }
    catch(err){
        console.error(err);
    }
}

const updateTask=async (req,res)=>{
       let id=req.query.id;
       var dbquery=`UPDATE public.task
       SET task_name='${req.body.task_name}', description='${req.body.description}', status='${req.body.status}',
        completed_date='${req.body.completed_date}', created_date='${req.body.created_date}'
       WHERE id=${id}`
        let dbresult=await db.query(dbquery);
        res.json(req.params);
}

const deleteTask=async (req,res)=>{
        let id=req.query.id;
        var dbquery=`delete from Task where id=${id}`;
        let dbresult=await db.query(dbquery);
        res.json(req.params);
}

module.exports={gettask,posttask,updateTask,deleteTask}

4.Creating Routes and Task Routes


add new folder named routes and create a file to handle taskroutes as taskroutes.js

routes/taskroutes.js


const task = require('../datalayer/task')

const taskroute=(app)=>{
    app.get('/gettasks',async (req,res)=>{
        return await task.gettask(req,res);
    });

    app.post('/createtask',async (req,res)=>{
        return await task.posttask(req,res);
    });

    app.put('/updatetask',async (req,res)=>{
        return await task.updateTask(req,res);
    });

    app.delete('/deletetask',async (req,res)=>{
        return await task.deleteTask(req,res);
    })
}

module.exports=taskroute

Do changes in index,js to handle the errors:


index.js


const expressrequire('express');
const appexpress();
const PORT=3002;
const taskroutesrequire('./routes/taskroutes')

app.use(express.json());//middleware to handle json req body

taskroutes(app);

app.get('/',(req,res)=>{
    res.json('Hello world');
});

app.listen(PORT,()=>{
    console.log('Started web server at port'+PORT);
})

Final project structure:


sp2

Now the project is ready we can run the project by command in terminal:"node index"

5. Running and Testing in POSTMAN:


GetTasks:

alt1



CreateTask:

alt2


UpdateTask:


alt3

DeleteTask:

alt4


Thanks for Reading. All the best for your learning.

My Popular Posts:




Youtube channel links
















Post a Comment

1 Comments

  1. Thanks for reading. we will continue posting more knowledge based blogs.

    ReplyDelete