{"id":14678,"date":"2020-09-08T13:00:17","date_gmt":"2020-09-08T11:00:17","guid":{"rendered":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/"},"modified":"2020-09-08T13:00:17","modified_gmt":"2020-09-08T11:00:17","slug":"build-api-backend-server-with-nodejs-and-postgresql","status":"publish","type":"post","link":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/","title":{"rendered":"Build API backend server with NodeJS and PostgreSQL"},"content":{"rendered":"<p><strong>Introduction<\/strong><\/p>\n<p>In this Blog I will describe how to create an API Backend with NodeJS using PostgreSQL as Database. We will create API for public events with CRUD options. CRUD means: create, read, update and delete. Firstly, we will create our PostgreSQL Tables and history tables. And then we will continue with NodeJS.<\/p>\n<p>If you don\u2019t have PostgreSQL installed yet, please follow these steps in our <a href=\"https:\/\/www.dbi-services.com\/blog\/handling-postgresql-installation-from-packages-internal-activity\/\" target=\"_blank\" rel=\"noopener noreferrer\">Blog<\/a>. As alternative you can also follow the steps in <a href=\"https:\/\/www.postgresql.org\/download\/\" target=\"_blank\" rel=\"noopener noreferrer\">PostgreSQL Page<\/a>. As Database client I will use <a href=\"https:\/\/dbeaver.io\/\" target=\"_blank\" rel=\"noopener noreferrer\">DBeaver<\/a> to create the tables.<\/p>\n<p>After you installed PostgreSQL we need to create database from the psql client. For that open terminal.<\/p>\n<pre class=\"brush: actionscript3; gutter: false; first-line: 1\">psql -U postgres\npostgres=# \n\npostgres=# create database events;\n\npostgres=# \\q\n<\/pre>\n<p>Now we can connect with our DBeaver client.<\/p>\n<p><a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43045\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png\" alt=\"\" width=\"300\" height=\"229\" \/><\/a><\/p>\n<p><a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43047\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL2.png\" alt=\"\" width=\"300\" height=\"256\" \/><\/a><\/p>\n<p><a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-43048\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL3.png\" alt=\"\" width=\"296\" height=\"150\" \/><\/a><\/p>\n<p>PostgreSQL is creating public schema by default. I recommended to delete it.<\/p>\n<p><a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL5.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43050\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL5.png\" alt=\"\" width=\"266\" height=\"300\" \/><\/a><\/p>\n<p>Now we can create our events table. For that open new SQL-Editor.<\/p>\n<p><a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL4.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43054\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL4.png\" alt=\"\" width=\"300\" height=\"199\" \/><\/a><\/p>\n<pre class=\"brush: sql; gutter: false; first-line: 1\">CREATE SCHEMA data;\n\ncreate sequence data.seq_events start with 1;\ncreate table data.events\n  ( id int primary key default nextval ('data.seq_events')\n  , title varchar(255) not null\n  , description varchar(255) not null\n  , price varchar(255) not null\n  , organizator varchar(255) not null\n  , startdate date not null\n  , starttime time not null\n  , endtime time not null\n  , location_name varchar(255) not null\n  , location_street varchar(255) not null\n  , location_zipcode varchar(255) not null\n  , location_city varchar(255) not null\n  , location_country varchar(255) not null\n  , created_at date default now()\n  , updated_at date default now()\n);\n\ncreate sequence data.history_seq_events start with 1;\ncreate table data.history_events\n  ( id int primary key default nextval ('data.history_seq_events')\n  , event_id int\n  , title varchar(255) not null\n  , description varchar(255) not null\n  , price varchar(255) not null\n  , organizator varchar(255) not null\n  , startdate date not null\n  , starttime time not null\n  , endtime time not null\n  , location_name varchar(255) not null\n  , location_street varchar(255) not null\n  , location_zipcode varchar(255) not null\n  , location_city varchar(255) not null\n  , location_country varchar(255) not null\n  , created_at date\n  , updated_at date\n);\n<\/pre>\n<p>Also create the trigger to save all changes automatically into the history table<\/p>\n<pre class=\"brush: sql; gutter: false; first-line: 1\">create function data.tf_update_events_history()\n  returns trigger\n\tlanguage plpgsql\n\tas\n$$\nbegin\n  insert into data.history_events\n    ( event_id\n  \t, title\n  \t, description\n  \t, price\n  \t, organizator\n  \t, startdate\n  \t, starttime\n  \t, endtime\n  \t, location_name\n  \t, location_street\n  \t, location_zipcode\n  \t, location_city\n  \t, location_country\n  \t, created_at\n  \t, updated_at \n    )\n  values\n    ( old.id\n  \t, old.title\n  \t, old.description\n  \t, old.price\n  \t, old.organizator\n  \t, old.startdate\n  \t, old.starttime\n  \t, old.endtime\n  \t, old.location_name\n  \t, old.location_street\n  \t, old.location_zipcode\n  \t, old.location_city\n  \t, old.location_country\n  \t, old.created_at\n  \t, old.updated_at \n    );\n   return new;\nend\n$$;\n-- trigger before update\ncreate trigger t_before_update_log_event_history\nbefore update on data.events\nfor each row\nexecute procedure data.tf_update_events_history();\n<\/pre>\n<p>And finally, we can test if our history trigger is working<\/p>\n<pre class=\"brush: sql; gutter: false; first-line: 1\">insert into data.events\n    ( title\n  \t, description\n  \t, price\n  \t, organizator\n  \t, startdate\n  \t, starttime\n  \t, endtime\n  \t, location_name\n  \t, location_street\n  \t, location_zipcode\n  \t, location_city\n  \t, location_country\n    )\n  values\n    ( 'PostgreSQL tutorial'\n    , 'In this event we will show PostgreSQL'\n  \t, 'Free'\n  \t, 'dbi services'\n  \t, '2020-11-16'\n  \t, '09:00'\n  \t, '17:00'\n  \t, 'dbi services sa'\n  \t, 'Flurstrasse 30'\n  \t, '8048'\n  \t, 'Z\u00fcrich'\n  \t, 'Switzerland'\n   );\n\nupdate data.events\nset startdate = '2020-11-20'\nwhere id = 1<\/pre>\n<p>Now once you open the history_events table you should see the old value.<\/p>\n<p><a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL21.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43055\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL21.png\" alt=\"\" width=\"300\" height=\"54\" \/><\/a><\/p>\n<p>Well done, it is working.<\/p>\n<p>Let\u2019s prepare our NodeJS environment.<\/p>\n<p>You can install NodeJS from <a href=\"https:\/\/nodejs.org\/en\/\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/nodejs.org\/en\/<\/a><\/p>\n<p>I will use Visual Studio Code editor. <a href=\"https:\/\/code.visualstudio.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/code.visualstudio.com\/<\/a><\/p>\n<p>Create any folder and open it in Visual Studio Code Editor.<\/p>\n<p><a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL7.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43058\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL7.png\" alt=\"\" width=\"266\" height=\"300\" \/><\/a><\/p>\n<p>Open Terminal and initial the Project:<\/p>\n<pre class=\"brush: bash; gutter: false; first-line: 1\">npm init -y<\/pre>\n<p>After that create the folders and files<\/p>\n<pre class=\"brush: bash; gutter: false; first-line: 1\">mkdir configs controllers db routes services validators &amp;&amp; touch .env index.js<\/pre>\n<p><strong>routes<\/strong>: Our all routes will be defined here<br \/>\n<strong>controllers<\/strong>: Each route has own controller, controller handles the request and response and calls multiple services. Controllers will never access to the Database!<br \/>\n<strong>validators<\/strong>: Validators Objects<br \/>\n<strong>services<\/strong>: runs one service, for example get data from the Database<br \/>\n<strong>configs<\/strong>: Object with configs, reads environment file attributes<br \/>\n<strong>db<\/strong>: Database Models and connection<br \/>\n<strong>.env<\/strong>: Environment variables such as PostgreSQL connection<br \/>\n<strong>index.js<\/strong>: Main File<\/p>\n<p>Now were ready to install the required dependencies:<\/p>\n<pre class=\"brush: bash; gutter: false; first-line: 1\">npm i express dotenv sequelize pg joi &amp;&amp; npm i --save-dev nodemon<\/pre>\n<p><strong>express<\/strong>: Framework to handle requests and responses<br \/>\n<strong>dotenv<\/strong>: Reads from .env file and adds into process variable which is readable globally<br \/>\n<strong>sequelize<\/strong>: Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, <strong>relations<\/strong>, eager and lazy loading, read replication and more.<br \/>\n<strong>pg<\/strong>: NodeJS PostgreSQL connection \u201cdriver\u201d<br \/>\n<strong>joi<\/strong>: For validation<br \/>\n<strong>nodemon<\/strong>: Restarts the server automatically on each file changes<\/p>\n<p><strong>&#8211;save-dev<\/strong> dependencies will be not installed on production environment.<\/p>\n<p>Firstly configure the nodemon, for that open package.json and into scripts<\/p>\n<pre class=\"brush: actionscript3; gutter: false; first-line: 1\">\"start\": \"nodemon index.js\"<\/pre>\n<p><a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL9.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43062\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL9.png\" alt=\"\" width=\"300\" height=\"126\" \/><\/a><\/p>\n<p>And then configure our .env file<\/p>\n<pre class=\"brush: actionscript3; gutter: false; first-line: 1\">NODE_ENV=development\nPORT=2000\n\nDB_HOST='localhost'\nDB_USERNAME='postgres'\nDB_PASSWORD='postgres'\nDB_DATABASE='events'\nDB_PORT=5432\nDB_DIALECT='postgres'<\/pre>\n<p>Then, create inside the configs folder file named &#8220;config.js&#8221; and insert:<\/p>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\">require('dotenv').config();\n\nvar config = {};\n\n\/\/ General config\nconfig.node_env = process.env.NODE_ENV;\n\n\/\/ WEB config\nconfig.web = {};\nconfig.web.port = process.env.PORT;\n\n\/\/ DB config\nconfig.db = {};\nconfig.db.host = process.env.DB_HOST;\nconfig.db.username = process.env.DB_USERNAME;\nconfig.db.password = process.env.DB_PASSWORD;\nconfig.db.database = process.env.DB_DATABASE;\nconfig.db.port = process.env.DB_PORT;\nconfig.db.dialect = process.env.DB_DIALECT;\n\nmodule.exports = config;<\/pre>\n<p>Inside db folder, create two files: &#8220;index.js&#8221; and &#8220;event.js&#8221;<\/p>\n<p>Open index.js file and insert:<\/p>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\">\/* Databse connection\n******************************************************************\/\n'use strict';\nconst { Sequelize } = require('sequelize');\nconst config = require('..\/configs\/config');\nconst db = {};\n\nconst sequelize = new Sequelize(\n  config.db.database,\n  config.db.username,\n  config.db.password,\n  {\n    host: config.db.host,\n    dialect: config.db.dialect,\n    logging: false\n  }\n);\n\n\/* init models\n******************************************************************\/\ndb.sequelize = sequelize\n\ndb.Events = require('.\/event')(sequelize)\n\nmodule.exports = db;<\/pre>\n<p>After that open event.js<\/p>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\">'use strict';\nconst {  Model, DataTypes } = require('sequelize');\n\nmodule.exports = (sequelize) =&gt; {  \n  class Events extends Model {}\n\n  Events.init({\n    id: {\n      type: DataTypes.INTEGER,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    title: {\n      type: DataTypes.STRING(255),\n      allowNull: false\n    },\n    description: {\n      type: DataTypes.STRING(255),\n      allowNull: false\n    },\n    price: {\n      type: DataTypes.STRING(255),\n      allowNull: false\n    },\n    organizator: {\n      type: DataTypes.STRING(255),\n      allowNull: false\n    },\n    startdate: {\n      type: DataTypes.DATEONLY,\n      allowNull: false\n    },\n    starttime: {\n      type: DataTypes.TIME,\n      allowNull: false\n    },\n    endtime: {\n      type: DataTypes.TIME,\n      allowNull: false\n    },\n    location_name: {\n      type: DataTypes.STRING(255),\n      allowNull: false\n    },\n    location_street: {\n      type: DataTypes.STRING(255),\n      allowNull: false\n    },\n    location_zipcode: {\n      type: DataTypes.STRING(255),\n      allowNull: false\n    },\n    location_city: {\n      type: DataTypes.STRING(255),\n      allowNull: false\n    },\n    location_country: {\n      type: DataTypes.STRING(255),\n      allowNull: false\n    },\n  }, {\n    tableName: 'events',\n    schema: 'data',\n    sequelize,\n    modelName: 'Events',\n    createdAt: 'created_at',\n    updatedAt: 'updated_at'\n  });\n\n  return Events\n};<\/pre>\n<p>Now we can create our two validators. One is for creating an event and the other is for updating.<br \/>\nCreate two two file inside the validators folder: &#8220;eventCreate.js&#8221; and &#8220;eventUpdate.js<\/p>\n<p>Open <strong>eventCreate.js<\/strong> and insert:<\/p>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\">const Joi = require('joi')\n\nmodule.exports = EventCreateValidator = Joi.object({\n    title: Joi.string().required(),\n    description: Joi.string().required(),\n    price: Joi.string().required(),\n    organizator: Joi.string().required(),\n    startdate: Joi.string().required(),\n    starttime: Joi.string().required(),\n    endtime: Joi.string().required(),\n    location_name: Joi.string().required(),\n    location_street: Joi.string().required(),\n    location_zipcode: Joi.string().required(),\n    location_city: Joi.string().required(),\n    location_country: Joi.string().required(),\n    created_at: Joi.string(),\n    updated_at: Joi.string(),\n})<\/pre>\n<p>Open <strong>eventUpdate.js<\/strong> and insert:<\/p>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\">const Joi = require('joi')\n\nmodule.exports = EventUpdateValidator = Joi.object({\n    title: Joi.string(),\n    description: Joi.string(),\n    price: Joi.string(),\n    organizator: Joi.string(),\n    startdate: Joi.string(),\n    starttime: Joi.string(),\n    endtime: Joi.string(),\n    location_name: Joi.string(),\n    location_street: Joi.string(),\n    location_zipcode: Joi.string(),\n    location_city: Joi.string(),\n    location_country: Joi.string(),\n    created_at: Joi.string(),\n    updated_at: Joi.string(),\n})<\/pre>\n<p>As you can see on creating event there is all fields required. But if we want to update, no field is requried.<br \/>\nCreate <strong>event.service.js<\/strong> inside the services folder and insert:<\/p>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\">const db = require('..\/db\/index')\n\nmodule.exports = {\n    async getEvents() {\n        try {\n            let events = await db.Events.findAll()\n            return events\n        } catch (e) {\n            throw e\n        }\n    },\n\n    async createEvent(event){\n        try {\n            let newEvent = await db.Events.create(event)\n            return newEvent\n        } catch (e) {\n            throw e\n        }\n    },\n\n    async updateEvent(id, event){\n        try {\n            let updateEvent = await db.Events.update(event, {\n                where: {\n                    id: id\n                }\n            })\n            return updateEvent\n        } catch (e) {\n            throw e\n        }\n    },\n\n    async deleteEvent(id){\n        try {\n            let deleteEvent = await db.Events.destroy({\n                where: {\n                    id: id\n                }\n            })\n            if(deleteEvent){\n                return true\n            } else {\n                return false\n            }\n        } catch (e) {\n            console.log(e)\n            throw e\n        }\n    }\n}<\/pre>\n<p>Now we can create the controller: create a file named &#8220;<strong>event.controller.js&#8221;<\/strong> inside the controllers folder and insert:<\/p>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\">const eventCreate = require('..\/validators\/eventCreate')\nconst eventUpdate = require('..\/validators\/eventUpdate')\nconst eventService = require('..\/services\/event.service')\n\nmodule.exports = {\n\n    \/* get All events *\/\n    async getEvents(req, res) {\n        try {\n            let events = await eventService.getEvents()\n            res.send(events)\n        } catch (e) {\n            res.send('Internal server error')\n        }\n    },\n\n    \/* add event *\/\n    async addEvent(req, res) {\n        try {\n            const { body } = req\n\n            \/* validate input *\/\n            let inputIsValid = await eventCreate.validate(body)\n\n            if(inputIsValid.error){\n                res.send(inputIsValid.error.details[0].message)\n            } else {\n                let createdEvent = await eventService.createEvent(body)\n                res.send(createdEvent)\n            }\n        } catch (e) {\n            res.send('Internal server error')\n        }\n    },\n\n    async updateEventById(req, res) {\n        try {\n            const { body } = req\n            const { id } = req.params\n\n            \/* validate input *\/\n            let inputIsValid = await eventUpdate.validate(body)\n\n            if(inputIsValid.error){\n                res.send(inputIsValid.error.message[0].details)\n            } else {\n                let updateEvent = await eventService.updateEvent(id, body)\n                res.send(updateEvent)\n            }\n        } catch (e) {\n            res.send('Internal server error')\n        }\n    },\n\n    async deleteEventById(req, res) {\n        try {\n            const { id } = req.params\n            let deleteEvent = await eventService.deleteEvent(id)\n            res.send(deleteEvent)\n        } catch (e) {\n            res.send('Internal server error')\n        }\n    },\n}\n\nAt least we need to create our routes. Create two files inside the routes folder: \"<strong>index.js\" <\/strong>and \"<strong>event.router.js\". \n<\/strong>Open \"<strong>event.router.js\" <\/strong>and insert:\n<\/pre>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\">\/\/index router\nconst express = require('express');\nconst eventController = require('..\/controllers\/event.controller');\nconst router = express.Router();\n\n\/* get events *\/\nrouter.get('\/', eventController.getEvents)\n\n\/* post new event *\/\nrouter.post('\/', eventController.addEvent)\n\n\/* update event by id *\/\nrouter.put('\/:id', eventController.updateEventById)\n\n\/* delete event by id *\/\nrouter.delete('\/:id', eventController.deleteEventById)\n\nmodule.exports = router\n\nAt least open the \"<strong>index.js<\/strong>\" inside the routers folder and insert:<\/pre>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\">\/\/index router\nconst express = require('express');\nconst router = express.Router();\nconst eventsRouter = require('.\/event.router')\n\nrouter.use('\/events', eventsRouter)\n\nmodule.exports = router<\/pre>\n<p>And Finally, we can update our main index.js file:<\/p>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\">const express = require('express')\nconst routes = require('.\/routes\/index')\nconst config = require('.\/configs\/config')<\/pre>\n<p>const app = express()<\/p>\n<p>\/\/ parse requests of content-type &#8211; application\/json<br \/>\napp.use(express.json())<\/p>\n<p>\/\/ load routes<br \/>\napp.use(&#8216;\/api&#8217;, routes)<\/p>\n<p>app.listen(config.web.port, () =&gt; {<br \/>\nconsole.log(`server is running at port ${config.web.port}`)<br \/>\n})<\/p>\n<p>Done. Now we can test our API Endpoints. I will use <a href=\"https:\/\/www.postman.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">Postman<\/a><\/p>\n<p>First test our \/api\/events endpoint:<br \/>\n<a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL12.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43065\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL12.png\" alt=\"\" width=\"234\" height=\"300\" \/><\/a><br \/>\nYeaah it is working!<br \/>\nSecond, test our put \/api\/events\/:id endpoint:<br \/>\nFor that you need to set headers as below:<br \/>\n<a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL13.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43067\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL13.png\" alt=\"\" width=\"300\" height=\"95\" \/><\/a><\/p>\n<p>Now we can update:<\/p>\n<p><a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL14.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43069\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL14.png\" alt=\"\" width=\"300\" height=\"133\" \/><\/a><\/p>\n<p>Now we can try to add new event. First try to add an empty Object. The Validation should throw error.<\/p>\n<p><a href=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL18.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-43072\" src=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL18.png\" alt=\"\" width=\"300\" height=\"142\" \/><\/a><\/p>\n<p>As aspected it is throwing error.<\/p>\n<p><strong>Conclusion:<\/strong><\/p>\n<p>I hope you did understand the main concept. For production you might be protect the delete and put endpoints by allowing only authenticated users. For that you need to implement JWT or session Authentication.<\/p>\n<pre class=\"brush: javascript; gutter: false; first-line: 1\"><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Introduction In this Blog I will describe how to create an API Backend with NodeJS using PostgreSQL as Database. We will create API for public events with CRUD options. CRUD means: create, read, update and delete. Firstly, we will create our PostgreSQL Tables and history tables. And then we will continue with NodeJS. If you [&hellip;]<\/p>\n","protected":false},"author":28,"featured_media":14679,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[83],"tags":[],"type_dbi":[],"class_list":["post-14678","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-postgresql"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.2 (Yoast SEO v27.2) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Build API backend server with NodeJS and PostgreSQL - dbi Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Build API backend server with NodeJS and PostgreSQL\" \/>\n<meta property=\"og:description\" content=\"Introduction In this Blog I will describe how to create an API Backend with NodeJS using PostgreSQL as Database. We will create API for public events with CRUD options. CRUD means: create, read, update and delete. Firstly, we will create our PostgreSQL Tables and history tables. And then we will continue with NodeJS. If you [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/\" \/>\n<meta property=\"og:site_name\" content=\"dbi Blog\" \/>\n<meta property=\"article:published_time\" content=\"2020-09-08T11:00:17+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"745\" \/>\n\t<meta property=\"og:image:height\" content=\"569\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Open source Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Open source Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/\"},\"author\":{\"name\":\"Open source Team\",\"@id\":\"https:\/\/www.dbi-services.com\/blog\/#\/schema\/person\/59554f0d99383431eb6ed427e338952b\"},\"headline\":\"Build API backend server with NodeJS and PostgreSQL\",\"datePublished\":\"2020-09-08T11:00:17+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/\"},\"wordCount\":690,\"commentCount\":0,\"image\":{\"@id\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png\",\"articleSection\":[\"PostgreSQL\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/\",\"url\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/\",\"name\":\"Build API backend server with NodeJS and PostgreSQL - dbi Blog\",\"isPartOf\":{\"@id\":\"https:\/\/www.dbi-services.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png\",\"datePublished\":\"2020-09-08T11:00:17+00:00\",\"author\":{\"@id\":\"https:\/\/www.dbi-services.com\/blog\/#\/schema\/person\/59554f0d99383431eb6ed427e338952b\"},\"breadcrumb\":{\"@id\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#primaryimage\",\"url\":\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png\",\"contentUrl\":\"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png\",\"width\":745,\"height\":569},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Accueil\",\"item\":\"https:\/\/www.dbi-services.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Build API backend server with NodeJS and PostgreSQL\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.dbi-services.com\/blog\/#website\",\"url\":\"https:\/\/www.dbi-services.com\/blog\/\",\"name\":\"dbi Blog\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.dbi-services.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.dbi-services.com\/blog\/#\/schema\/person\/59554f0d99383431eb6ed427e338952b\",\"name\":\"Open source Team\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/secure.gravatar.com\/avatar\/eb4fb12e386e8c41fdef0733e8114594cf2653e4f55e9fa2161442b8eaf3f657?s=96&d=mm&r=g\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/eb4fb12e386e8c41fdef0733e8114594cf2653e4f55e9fa2161442b8eaf3f657?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/eb4fb12e386e8c41fdef0733e8114594cf2653e4f55e9fa2161442b8eaf3f657?s=96&d=mm&r=g\",\"caption\":\"Open source Team\"},\"url\":\"https:\/\/www.dbi-services.com\/blog\/author\/open-source-team\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Build API backend server with NodeJS and PostgreSQL - dbi Blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/","og_locale":"en_US","og_type":"article","og_title":"Build API backend server with NodeJS and PostgreSQL","og_description":"Introduction In this Blog I will describe how to create an API Backend with NodeJS using PostgreSQL as Database. We will create API for public events with CRUD options. CRUD means: create, read, update and delete. Firstly, we will create our PostgreSQL Tables and history tables. And then we will continue with NodeJS. If you [&hellip;]","og_url":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/","og_site_name":"dbi Blog","article_published_time":"2020-09-08T11:00:17+00:00","og_image":[{"width":745,"height":569,"url":"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png","type":"image\/png"}],"author":"Open source Team","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Open source Team","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#article","isPartOf":{"@id":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/"},"author":{"name":"Open source Team","@id":"https:\/\/www.dbi-services.com\/blog\/#\/schema\/person\/59554f0d99383431eb6ed427e338952b"},"headline":"Build API backend server with NodeJS and PostgreSQL","datePublished":"2020-09-08T11:00:17+00:00","mainEntityOfPage":{"@id":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/"},"wordCount":690,"commentCount":0,"image":{"@id":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#primaryimage"},"thumbnailUrl":"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png","articleSection":["PostgreSQL"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/","url":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/","name":"Build API backend server with NodeJS and PostgreSQL - dbi Blog","isPartOf":{"@id":"https:\/\/www.dbi-services.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#primaryimage"},"image":{"@id":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#primaryimage"},"thumbnailUrl":"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png","datePublished":"2020-09-08T11:00:17+00:00","author":{"@id":"https:\/\/www.dbi-services.com\/blog\/#\/schema\/person\/59554f0d99383431eb6ed427e338952b"},"breadcrumb":{"@id":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#primaryimage","url":"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png","contentUrl":"https:\/\/www.dbi-services.com\/blog\/wp-content\/uploads\/sites\/2\/2022\/04\/NodeJS_PostgreSQL1.png","width":745,"height":569},{"@type":"BreadcrumbList","@id":"https:\/\/www.dbi-services.com\/blog\/build-api-backend-server-with-nodejs-and-postgresql\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Accueil","item":"https:\/\/www.dbi-services.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Build API backend server with NodeJS and PostgreSQL"}]},{"@type":"WebSite","@id":"https:\/\/www.dbi-services.com\/blog\/#website","url":"https:\/\/www.dbi-services.com\/blog\/","name":"dbi Blog","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.dbi-services.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.dbi-services.com\/blog\/#\/schema\/person\/59554f0d99383431eb6ed427e338952b","name":"Open source Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/eb4fb12e386e8c41fdef0733e8114594cf2653e4f55e9fa2161442b8eaf3f657?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/eb4fb12e386e8c41fdef0733e8114594cf2653e4f55e9fa2161442b8eaf3f657?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/eb4fb12e386e8c41fdef0733e8114594cf2653e4f55e9fa2161442b8eaf3f657?s=96&d=mm&r=g","caption":"Open source Team"},"url":"https:\/\/www.dbi-services.com\/blog\/author\/open-source-team\/"}]}},"_links":{"self":[{"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/posts\/14678","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/users\/28"}],"replies":[{"embeddable":true,"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/comments?post=14678"}],"version-history":[{"count":0,"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/posts\/14678\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/media\/14679"}],"wp:attachment":[{"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/media?parent=14678"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/categories?post=14678"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/tags?post=14678"},{"taxonomy":"type","embeddable":true,"href":"https:\/\/www.dbi-services.com\/blog\/wp-json\/wp\/v2\/type_dbi?post=14678"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}