PostgreSQL and REST API

Preconditions:

=> Download NodeJS from https://nodejs.org/en/download

=> Download and install PostgreSQL from https://www.postgresql.org/download/windows/

=> Good to have Postman installed as well from https://www.postman.com/downloads/

=> Be familiar with JavaScript from https://www.hemelix.com/scada-hmi/twincat-hmi/twincat-hmi-async-function/

 

We can check if those are installed already:

=> Checking if postgres installed

postgres --version

=> Check if the nodeJS installed

node -v

 

Once we have installed PostgreSQL, we can create and build a REST API.

=> Create a folder name Hemelix_RestAPI (File |  Open folder)

=> Fire Visual Studio Code and create a folder called REST API

=> Open a terminal (Terminal | New Terminal) and run the following command

npm init -y 

=> Hit enter and it will create a JSON file called package.json file under the REST API folder

=> Install express framework by executing the following command

npm i --save express

=> Install PostgreSQl connector by executing the following command

npm i pg

Now create the structure of the folder of your project as you need.

=> Create a file called server.js with the following content

const express = require("express");
const app= express();
const port = 3000;
app.get("/", (req, res) => {
    res.send("Hello World, so far so good!");
});
app.listen(port, () => console.log(`app listening on port ${port}`));

=> The console can be cleaned by typing

clear

CRUD stands for Create, Read, Update, and Delete

These are the four fundamental operations used to manage data in a database or software application.

CRUD

Description

SQL command

REST API method

C – Create

Insert new data

INSERT

POST

R – Read

Retrieve existing data

SELECT

GET

U – Update

Modify existing data

UPDATE

PUT / PATCH

D – Delete

Remove existing data

DELETE

DELETE

=> https://www.hemelix.com/software/visual-studio-code/ (How to start with VS Code)

=> https://www.hemelix.com/sql/react-ui-tutorial/ (REACT tutorial for UI )

Run the existing Sample

Download Hemelix_RestAPI.zip

If we have a project, open it in Visual Studio Code and run the following command.

node .\server.js

http://localhost:3000/  //Insert this in the browser and get the response Hello World

http://localhost:3000/API/V1/students  //Insert this in the browser and get all students as a response

http://localhost:3000/API/V1/students/2/  //Get student by ID

Before executing or calling the API, we must create a table: students

Databases | Create-Database (Fill the boxes) | Save

Register a PostgreSQL Server in pgAdmin

If we want to connect to a database, we need to register the pgServer. To connect to a PostgreSQL database using pgAdmin, we first need to register the PostgreSQL server. Server registration involves configuring the connection parameters, such as the host address, port number, username, and password. Once the connection is established, we can access and manage the databases hosted on that server. 

Information required to register a server

Parameter

Example

Description

Name

My PostgreSQL Server

User-defined connection name

Host name/address

192.168.1.100

IP address or computer name

Port

5432

Default PostgreSQL port

Maintenance database

postgres

Initial database for connection

Username

postgres

PostgreSQL user

Password

********

User’s password

Postman

Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration. It is a development tool where we can test our REST API without using a browser.

Tips

01: How to Reset Forgotten Password for PostgreSQL User

=> Go to C:\Program Files\PostgreSQL\16\data and open pg_hba.conf  file

=> Change the content below METHOD to trust

=> Open the service and start postgresql-x64-16

=> Type in Windows search SQL and select (SQL Shell (psql) )

=> Configure by using SQL Shell (psql) just by pressing enter

=> Finally, execute the following command 

postgres=# ALTER USER postgres WITH PASSWORD 'my_secret_pass';

02: List a user table in the PG database

postgres=# \l

03: Connection Status PG database

postgres=# \conninfo  => You are connected to database “postgres” as user “postgres” on host “localhost” (address “::1”) at port “5432”.

04: Create PG database

postgres=# CREATE DATABASE students;

=> show list of tables

\l

05: Connect to Database

postgres=# \c students

06: Create Table

CREATE TABLE students (ID SERIAL PRIMARY KEY, name VARCHAR(255), email VARCHAR(255),age INT, dob DATE);

07: Display Table

postgres=# \dt

08: Insert data into the table

INSERT INTO students(name, email, age, dob) VALUES (‘Joe’, ‘joe@gmail.com’, 48, ‘1973-04-04’), (‘Anna’, ‘anna@gmail.com’, 23, ‘2000-01-01’);

09: Display Table Data

postgres=# SELECT * FROM students;

10: Clear the screen

postgres=# \! cls

References

See Also :