<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rahul Gupta on Medium]]></title>
        <description><![CDATA[Stories by Rahul Gupta on Medium]]></description>
        <link>https://medium.com/@rahulguptalive?source=rss-57434d4ef68a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*5_JMCD-t2uPU7L3BrltcEw.jpeg</url>
            <title>Stories by Rahul Gupta on Medium</title>
            <link>https://medium.com/@rahulguptalive?source=rss-57434d4ef68a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:34:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahulguptalive/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Create CRUD APIs in NodeJS, Express and MySQL]]></title>
            <link>https://medium.com/@rahulguptalive/create-crud-apis-in-nodejs-express-and-mysql-abda4dfc2d6?source=rss-57434d4ef68a------2</link>
            <guid isPermaLink="false">https://medium.com/p/abda4dfc2d6</guid>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Rahul Gupta]]></dc:creator>
            <pubDate>Tue, 19 Nov 2019 13:35:22 GMT</pubDate>
            <atom:updated>2020-09-09T17:29:48.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*gCe-rlfc_3LVaxkaE2Zpvg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@goran_ivos">Goran Ivos</a> on <a href="https://unsplash.com/photos/iOykDIkZLQw">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/@rahulguptalive/how-to-build-simple-restful-crud-api-with-nodejs-expressjs-and-mongodb-2d25a0e27937">previous story</a> we learnt how to create restful crud(create, read, update, delete) api in nodejs, express and mongodb but now in this we’ll learn to create crud api in nodejs , express and mysql .</p><p><strong>Prerequisites and required applications</strong></p><p><a href="https://nodejs.org/"><strong>Node.js</strong></a> is an open source, cross-platform runtime environment for developing server-side and networking applications. You should have basic understanding of nodejs.</p><p><a href="https://expressjs.com/"><strong>Express</strong></a><strong>JS</strong> is one of the most trending web frameworks for node.js. It is built on top of node.js http module, and adds support for routing, middleware, view system etc. It is very simple and minimal, unlike other frameworks.</p><p><a href="https://www.mysql.com/"><strong>MySQL</strong></a> is an open-source relational database management system. Its name is a combination of “My”, the name of co-founder Michael Widenius’s daughter, and “SQL”, the abbreviation for Structured Query Language.</p><p><a href="https://www.w3schools.com/js/js_es6.asp"><strong>EcmaScript (ES)</strong></a> is a standardised scripting language for JavaScript (JS). The current ES version supported in modern browsers is ES5. However, ES6 tackles a lot of the limitations of the core language, making it easier for devs to code</p><p><a href="https://www.getpostman.com/"><strong>Postman</strong></a> is an API(application programming interface) development tool which helps to build, test and modify APIs.It has the ability to make various types of HTTP requests(GET, POST, PUT, PATCH etc.).</p><p><strong>IDE</strong> (<strong>integrated development environment)</strong> is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build automation tools, and a debugger<em>. </em>In case of mine<em>, </em>I<em> </em>prefer to use <a href="https://code.visualstudio.com/"><strong>visual studio code</strong></a>.</p><p><strong>Create a Project</strong></p><p>Now it’s time to create our project. Create a directory name NodeMysqlCrudApp<strong>. </strong>Then navigate to NodeMysqlCrudApp directory. Command are as below</p><pre>// Create directory<br>mkdir NodeMysqlCrudApp</pre><pre>// then Navigate to NodeMysqlCrudApp<br>cd NodeMysqlCrudApp</pre><p><strong>Initialise and Configure Our Project</strong></p><p>To initialise run the command in project folder npm init that will ask a few questions to avoid that you can run npm init -y . Finally package.json looks like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIB4QN1e5L9qJASUEhhXGg.png" /><figcaption>package.json</figcaption></figure><p><strong>Install express and other dependencies</strong></p><ul><li><strong>Express </strong>is top framework of nodejs. Install using below command :</li></ul><pre>npm install express --save</pre><ul><li><strong>Body Parser </strong>is Node.js body parsing middleware. Parse incoming request bodies in a middleware before your handlers, available under the req.body property.</li></ul><pre>npm install body-parser --save</pre><ul><li><strong>MySQL </strong>is open source database use to interacting with database and manipulating the records.</li></ul><pre>npm install mysql --save</pre><ul><li><strong>Nodemon </strong>is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected. Use -dev flag to save in devDependencies and --save will save the dependencies in package.json file.</li></ul><pre>npm install --save-dev nodemon</pre><p>Now package.json looks like as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*arMtO-kJyIp6dXc6bD3a2w.png" /><figcaption>package.json</figcaption></figure><h4>Start the web server</h4><p>As we earlier we have created enter point of application is server.js, we will create server.js file at the root of project folder.</p><pre>touch server.js</pre><p>Add some code in server.js file</p><pre>const express = require(&#39;express&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);</pre><pre>// create express app<br>const app = express();</pre><pre>// Setup server port<br>const port = process.env.PORT || 5000;</pre><pre>// parse requests of content-type - application/x-www-form-urlencoded<br>app.use(bodyParser.urlencoded({ extended: true }))</pre><pre>// parse requests of content-type - application/json<br>app.use(bodyParser.json())</pre><pre>// define a root route<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&quot;Hello World&quot;);<br>});</pre><pre>// listen for requests<br>app.listen(port, () =&gt; {<br>  console.log(`Server is listening on port ${port}`);<br>});</pre><p>Now run the web server using node server.js or node server command :</p><pre>node server.js</pre><pre>OR</pre><pre>node server</pre><p>Now open your favourite browser and navigate to <a href="http://localhost:5000/">http://localhost:5000</a> . Browser will show Hello World . That’s great now our server is running.</p><p>In previous step we had installed nodemon . If we want run the server using nodemon then we have to use the nodemon server.js or nodemon server command. Let’s do some change in package.json file , add a line of code in scripts object of package.json file.</p><pre>&quot;start&quot;: &quot;nodemon server&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7oZvjvG3Wty5nRe4hlaN0g.png" /><figcaption>package.json</figcaption></figure><p>Now simply run npm start to run the server that will auto restart the serve when detect any change in files.</p><pre>npm start</pre><p><strong>Create database</strong></p><pre>CREATE DATABASE node_mysql_crud_db;</pre><pre>CREATE  TABLE IF NOT EXISTS `employees` (<br>  `id` BIGINT UNSIGNED AUTO_INCREMENT,<br>  `first_name` VARCHAR(255) NOT NULL,<br>  `last_name` VARCHAR(255) NOT NULL,<br>  `email` VARCHAR(255) NOT NULL,<br>  `phone` VARCHAR(50) NOT NULL,<br>  `organization` VARCHAR(255) NOT NULL,<br>  `designation` VARCHAR(100) NOT NULL,<br>  `salary` DECIMAL(11,2) UNSIGNED DEFAULT 0.00,<br>  `status` TINYINT UNSIGNED DEFAULT 0,<br>  `is_deleted` TINYINT UNSIGNED DEFAULT 0,<br>  `created_at` DATETIME NOT NULL,<br>  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,<br>  PRIMARY KEY (`id`))<br>ENGINE = InnoDB;</pre><pre>INSERT INTO `node_mysql_crud_db`.`employees` (`first_name`, `last_name`, `email`, `phone`, `organization`, `designation`, `salary`, `status`, `is_deleted`, `created_at`) VALUES (&#39;John&#39;, &#39;Doe&#39;, &#39;<a href="/service/mailto:johndoe@gmail.com">johndoe@gmail.com</a>&#39;, &#39;1234567890&#39;, &#39;BR Softech Pvt Ltd&#39;, &#39;Full Stack Developer&#39;, &#39;500.00&#39;, &#39;1&#39;, &#39;0&#39;, &#39;2019-11-19 03:30:30&#39;);<br>INSERT INTO `node_mysql_crud_db`.`employees` (`first_name`, `last_name`, `email`, `phone`, `organization`, `designation`, `salary`, `status`, `is_deleted`, `created_at`) VALUES (&#39;Jane&#39;, &#39;Doe&#39;, &#39;<a href="/service/mailto:janedoe@gmail.com">janedoe@gmail.com</a>&#39;, &#39;9876543210&#39;, &#39;RG Infotech Jaipur&#39;, &#39;PHP Developer&#39;, &#39;450.00&#39;, &#39;1&#39;, &#39;0&#39;, &#39;2019-11-19 03:35:30&#39;);</pre><p><strong>Make database connection</strong></p><p>To make connectivity with database in our project we’ll make seperate file. So create a config folder at root and make a db.config.js file inside config folder.</p><pre>mkdir config<br>cd config<br>touch db.config.js</pre><p>Now open db.config.js and add code below for creating mysql connection.</p><pre>&#39;use strict&#39;;</pre><pre>const mysql = require(&#39;mysql&#39;);</pre><pre>//local mysql db connection</pre><pre>const dbConn = mysql.createConnection({</pre><pre>  host     : &#39;localhost&#39;,</pre><pre>  user     : &#39;root&#39;,</pre><pre>  password : &#39;&#39;,</pre><pre>  database : &#39;node_mysql_crud_db&#39;</pre><pre>});</pre><pre>dbConn.connect(function(err) {</pre><pre>  if (err) throw err;</pre><pre>  console.log(&quot;Database Connected!&quot;);</pre><pre>});</pre><pre>module.exports = dbConn;</pre><p><strong>Project Folder Structure</strong></p><p>Now folder structure of project like as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*OIj3inAJ704TRFG30f01mQ.png" /><figcaption>project directory structure</figcaption></figure><p>Complete employee.model.js file is here -</p><pre>&#39;use strict&#39;;</pre><pre>var dbConn = require(&#39;./../../config/db.config&#39;);</pre><pre>//Employee object create</pre><pre>var Employee = function(employee){</pre><pre>  this.first_name     = employee.first_name;</pre><pre>  this.last_name      = employee.last_name;</pre><pre>  this.email          = employee.email;</pre><pre>  this.phone          = employee.phone;</pre><pre>  this.organization   = employee.organization;</pre><pre>  this.designation    = employee.designation;</pre><pre>  this.salary         = employee.salary;</pre><pre>  this.status         = employee.status ? employee.status : 1;</pre><pre>  this.created_at     = new Date();</pre><pre>  this.updated_at     = new Date();</pre><pre>};</pre><pre>Employee.create = function (newEmp, result) {</pre><pre>dbConn.query(&quot;INSERT INTO employees set ?&quot;, newEmp, function (err, res) {</pre><pre>if(err) {</pre><pre>  console.log(&quot;error: &quot;, err);</pre><pre>  result(err, null);</pre><pre>}</pre><pre>else{</pre><pre>  console.log(res.insertId);</pre><pre>  result(null, res.insertId);</pre><pre>}</pre><pre>});</pre><pre>};</pre><pre>Employee.findById = function (id, result) {</pre><pre>dbConn.query(&quot;Select * from employees where id = ? &quot;, id, function (err, res) {</pre><pre>if(err) {</pre><pre>  console.log(&quot;error: &quot;, err);</pre><pre>  result(err, null);</pre><pre>}</pre><pre>else{</pre><pre>  result(null, res);</pre><pre>}</pre><pre>});</pre><pre>};</pre><pre>Employee.findAll = function (result) {</pre><pre>dbConn.query(&quot;Select * from employees&quot;, function (err, res) {</pre><pre>if(err) {</pre><pre>  console.log(&quot;error: &quot;, err);</pre><pre>  result(null, err);</pre><pre>}</pre><pre>else{</pre><pre>  console.log(&#39;employees : &#39;, res);</pre><pre>  result(null, res);</pre><pre>}</pre><pre>});</pre><pre>};</pre><pre>Employee.update = function(id, employee, result){</pre><pre>dbConn.query(&quot;UPDATE employees SET first_name=?,last_name=?,email=?,phone=?,organization=?,designation=?,salary=? WHERE id = ?&quot;, [employee.first_name,employee.last_name,employee.email,employee.phone,employee.organization,employee.designation,employee.salary, id], function (err, res) {</pre><pre>if(err) {</pre><pre>  console.log(&quot;error: &quot;, err);</pre><pre>  result(null, err);</pre><pre>}else{</pre><pre>  result(null, res);</pre><pre>}</pre><pre>});</pre><pre>};</pre><pre>Employee.delete = function(id, result){</pre><pre>dbConn.query(&quot;DELETE FROM employees WHERE id = ?&quot;, [id], function (err, res) {</pre><pre>if(err) {</pre><pre>  console.log(&quot;error: &quot;, err);</pre><pre>  result(null, err);</pre><pre>}</pre><pre>else{</pre><pre>  result(null, res);</pre><pre>}</pre><pre>});</pre><pre>};</pre><pre>module.exports= Employee;</pre><p>Here is complete employee.controller.js file -</p><pre>&#39;use strict&#39;;</pre><pre>const Employee = require(&#39;../models/employee.model&#39;);</pre><pre>exports.findAll = function(req, res) {</pre><pre>Employee.findAll(function(err, employee) {</pre><pre>  console.log(&#39;controller&#39;)</pre><pre>  if (err)</pre><pre>  res.send(err);</pre><pre>  console.log(&#39;res&#39;, employee);</pre><pre>  res.send(employee);</pre><pre>});</pre><pre>};</pre><pre>exports.create = function(req, res) {</pre><pre>const new_employee = new Employee(req.body);</pre><pre>//handles null error</pre><pre>if(req.body.constructor === Object &amp;&amp; Object.keys(req.body).length === 0){</pre><pre>  res.status(400).send({ error:true, message: &#39;Please provide all required field&#39; });</pre><pre>}else{</pre><pre>Employee.create(new_employee, function(err, employee) {</pre><pre>  if (err)</pre><pre>  res.send(err);</pre><pre>  res.json({error:false,message:&quot;Employee added successfully!&quot;,data:employee});</pre><pre>});</pre><pre>}</pre><pre>};</pre><pre>exports.findById = function(req, res) {</pre><pre>Employee.findById(req.params.id, function(err, employee) {</pre><pre>  if (err)</pre><pre>  res.send(err);</pre><pre>  res.json(employee);</pre><pre>});</pre><pre>};</pre><pre>exports.update = function(req, res) {</pre><pre>  if(req.body.constructor === Object &amp;&amp; Object.keys(req.body).length === 0){</pre><pre>    res.status(400).send({ error:true, message: &#39;Please provide all required field&#39; });</pre><pre>  }else{</pre><pre>    Employee.update(req.params.id, new Employee(req.body), function(err, employee) {</pre><pre>   if (err)</pre><pre>   res.send(err);</pre><pre>   res.json({ error:false, message: &#39;Employee successfully updated&#39; });</pre><pre>});</pre><pre>}</pre><pre>};</pre><pre>exports.delete = function(req, res) {</pre><pre>Employee.delete( req.params.id, function(err, employee) {</pre><pre>  if (err)</pre><pre>  res.send(err);</pre><pre>  res.json({ error:false, message: &#39;Employee successfully deleted&#39; });</pre><pre>});</pre><pre>};</pre><p>Here is complete employee.routes.js file -</p><pre>const express = require(&#39;express&#39;)</pre><pre>const router = express.Router()</pre><pre>const employeeController =   require(&#39;../controllers/employee.controller&#39;);</pre><pre>// Retrieve all employees</pre><pre>router.get(&#39;/&#39;, employeeController.findAll);</pre><pre>// Create a new employee</pre><pre>router.post(&#39;/&#39;, employeeController.create);</pre><pre>// Retrieve a single employee with id</pre><pre>router.get(&#39;/:id&#39;, employeeController.findById);</pre><pre>// Update a employee with id</pre><pre>router.put(&#39;/:id&#39;, employeeController.update);</pre><pre>// Delete a employee with id</pre><pre>router.delete(&#39;/:id&#39;, employeeController.delete);</pre><pre>module.exports = router</pre><p>Now finally complete server.js file here :</p><pre>const express = require(&#39;express&#39;);</pre><pre>const bodyParser = require(&#39;body-parser&#39;);</pre><pre>// create express app</pre><pre>const app = express();</pre><pre>// Setup server port</pre><pre>const port = process.env.PORT || 5000;</pre><pre>// parse requests of content-type - application/x-www-form-urlencoded</pre><pre>app.use(bodyParser.urlencoded({ extended: true }))</pre><pre>// parse requests of content-type - application/json</pre><pre>app.use(bodyParser.json())</pre><pre>// define a root route</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {</pre><pre>  res.send(&quot;Hello World&quot;);</pre><pre>});</pre><pre>// Require employee routes</pre><pre>const employeeRoutes = require(&#39;./src/routes/employee.routes&#39;)</pre><pre>// using as middleware</pre><pre>app.use(&#39;/api/v1/employees&#39;, employeeRoutes)</pre><pre>// listen for requests</pre><pre>app.listen(port, () =&gt; {</pre><pre>  console.log(`Server is listening on port ${port}`);</pre><pre>});</pre><p><strong>API End Points</strong></p><ol><li>GET /api/v1/employees: will give all employees stored in database</li><li>GET /api/v1/employees/&lt;employee_id&gt;: will give a specific employee with employee_id.</li><li>POST /api/v1/employees : create a employee</li><li>PATCH /api/v1/employees/&lt;employee_id&gt;: update a employee partially</li><li>DELETE /api/v1/employees/&lt;employee_id&gt;: delete a employee</li><li>PUT /api/v1/employees/&lt;employee_id&gt;: update a employee completely</li></ol><p><strong>APIs Test in Postman</strong></p><p>Creating a new employee api/v1/employees using POST method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*ththrUpa5H9bTHI7lnH3Rw.png" /></figure><p>Get all employees list api/v1/employees using GET method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*aDNBzOsaS-WxIUE-Nxx_8Q.png" /></figure><p>Get specific employee api/v1/employees/id using GET method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*ZBceTG3NDWTiMe_RHdQVeg.png" /></figure><p>Update specific employee api/v1/employees/id using PUT method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*zn77VymH6JPhgKRlvTV8KQ.png" /></figure><p>Delete specific employee api/v1/employees/id using DELETE method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*FRuHLPne-4qa9ZO96pJSoQ.png" /></figure><p>Watch the on YouTube:-</p><p><a href="https://youtu.be/zgQq-gNvKH0">https://youtu.be/zgQq-gNvKH0</a></p><p>You can find it on <a href="https://github.com/rahulguptafullstack/node-mysql-crud-app">git repository here</a>.</p><pre><a href="https://github.com/rahulguptafullstack/node-mysql-crud-app">https://github.com/rahulguptafullstack/node-mysql-crud-app</a></pre><p>Thank for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abda4dfc2d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build Simple RESTful CRUD API With NodeJS, ExpressJS And MongoDB]]></title>
            <link>https://medium.com/@rahulguptalive/how-to-build-simple-restful-crud-api-with-nodejs-expressjs-and-mongodb-2d25a0e27937?source=rss-57434d4ef68a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d25a0e27937</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Rahul Gupta]]></dc:creator>
            <pubDate>Mon, 18 Nov 2019 17:17:48 GMT</pubDate>
            <atom:updated>2019-11-19T11:12:08.651Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*is03VOyLARQ1sgfQDbH8cQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop">Fortis Fotopoulus</a> on <a href="https://unsplash.com/photos/LJ9KY8pIH3E">Unsplash</a></figcaption></figure><p>We’ll be start to build a <strong>RESTful</strong> <strong>CRUD</strong> (Create, Read, Update, Delete) API with <strong>Node.js</strong>, <strong>Express</strong> and <strong>MongoDB</strong>. Here we’ll use Mongoose for interacting with the <strong>MongoDB</strong> instance.</p><p><strong><em>Required applications</em></strong></p><p><a href="https://nodejs.org/"><strong>Node.js</strong></a> is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications. Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications.</p><p><a href="https://expressjs.com/"><strong>Express</strong></a><strong>JS</strong> is one of the most popular web frameworks for node.js. It is built on top of node.js http module, and adds support for routing, middleware, view system etc. It is very simple and minimal, unlike other frameworks that try do way to much, thereby reducing the flexibility for developers to have their own design choices.</p><p><a href="http://mongoosejs.com/"><strong>Mongoose</strong></a> is an ODM (Object Document Mapping) tool for Node.js and MongoDB. It helps you convert the objects in your code to documents in the database and vice versa.</p><p>Before proceeding to the next section, Please install <strong>MongoDB</strong> in your machine if you have not done already. Checkout the <a href="https://docs.mongodb.com/manual/administration/install-community/"><strong>official MogngoDB installation manua</strong>l</a> for any help with the installation.</p><p><a href="https://www.getpostman.com/"><strong>Postman</strong></a> is an API(application programming interface) development tool which helps to build, test and modify APIs.It has the ability to make various types of HTTP requests(GET, POST, PUT, PATCH etc.).</p><p><strong>IDE</strong> (<strong>integrated development environment)</strong> is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build automation tools, and a debugger — <em>Wikipedia.</em></p><p><strong><em>Environment check and setup</em></strong></p><p>We have check that required applications are installed or not. We’ll check Node, NPM and MongoDB to installed on machine. Now open your preferred terminal / command prompt to run.</p><p>Let’s check the node version on machine, run the below command and see the output</p><pre>node -v</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*qA9OkkhEmB87Tidufg2oyg.png" /></figure><p>Now Let’s check node package manager(npm) version and see the ouput</p><pre>npm -v</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-Tq6yh1MikaaM_WtzDWug.png" /></figure><p>Finally check MongoDB version and see the output</p><pre>mongo -version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*cfs3dJq2NrZkugrnh1eRRw.png" /></figure><p><strong>Creating</strong> <strong>Our Project</strong></p><p>Now we’ll create our project. First of all choose filesystem / drive on where we’ll create our project. After that we create a directory name <strong>NodeExpressAPI. </strong>Then navigate to <strong>NodeExpressAPI </strong>directory. Command are as below</p><pre>// Create directory for new project named NodeExpressAPI<br>mkdir NodeExpressAPI</pre><pre>// then Navigate to NodeExpressAPI<br>cd NodeExpressAPI<br></pre><p>Now initialise the node js using npm init</p><pre>npm init</pre><p>That will ask a few thing like project name, version, description, author name etc follow the setup, if you do not to add info manually then use npm init -y which will geneate package.json file automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*Uxsf9MOhcmxrnJ5isEdzKw.png" /></figure><p>After adding the info to command prompt finally accept the licence and you have write yes Then package.json will be created. Finally package.json will look like as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*jU1gBcwwnGG7cshCFzeLnw.png" /></figure><p><strong>Install express and other dependencies</strong></p><p>Now we have to install express, body-parser, mongoose and nodemon modules in our application. Let’s install them by following in single command:</p><pre>npm install express body-parser mongoose nodemon --save</pre><p>Now package.json look like below and --save~ will add in the dependencies in our project. Nodemon auto restart the server after changes in files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*1K0GZaMzfKdBcUKbcb_d6w.png" /></figure><h4>Setting up the web server</h4><p>As we earlier we have created enter point of application is server.js, we will create server.js file.</p><pre>touch server.js</pre><p>Now create web server using express now server.js file look like</p><pre>const express = require(&#39;express&#39;);</pre><pre>const bodyParser = require(&#39;body-parser&#39;);</pre><pre>// create express app</pre><pre>const app = express();</pre><pre>// Setup server port</pre><pre>const port = process.env.PORT || 4000;</pre><pre>// parse requests of content-type - application/x-www-form-urlencoded</pre><pre>app.use(bodyParser.urlencoded({ extended: true }))</pre><pre>// parse requests of content-type - application/json</pre><pre>app.use(bodyParser.json())</pre><pre>// define a root/default route</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {</pre><pre>  res.json({&quot;message&quot;: &quot;Hello World&quot;});</pre><pre>});</pre><pre>// listen for requests</pre><pre>app.listen(port, () =&gt; {</pre><pre>  console.log(`Node server is listening on port ${port}`);</pre><pre>});</pre><p>Now run the server and go to <a href="http://localhost:4000/">http://localhost:4000</a>to access the route. Response will like as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mo5YPu19QyJv1gQOANjXEg.png" /></figure><h4><strong>Connect to the database</strong></h4><p>We’ll keep all the configurations for the app in a separate folder. Let’s create a new folder config in the root of our applications.</p><pre>mkdir config<br>cd config</pre><p>Now, Create a new file db.config.js inside config folder with the following piece code -</p><pre>module.exports = {<br>    url: &#39;mongodb://localhost:27017/node-express-api&#39;<br>}</pre><p>Now we have start the mongodb-server for that open another terminal/command prompt window and run the below command -</p><pre>mongod</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFJ9Uk0JFDFhboRhZ2R4Fg.png" /></figure><p>We’ll now import the above database configuration in server.js and connect to the database using mongoose.</p><p>Add the following piece code to the server.js file after app.use(bodyParser.json()) line :</p><pre>node server.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0XanAHLMrdhSoh2qL7k1A.png" /></figure><p>Now server.js file look like as below</p><pre>const express = require(&#39;express&#39;);</pre><pre>const bodyParser = require(&#39;body-parser&#39;);</pre><pre>// create express app</pre><pre>const app = express();</pre><pre>// Setup server port</pre><pre>const port = process.env.PORT || 4000;</pre><pre>// parse requests of content-type - application/x-www-form-urlencoded</pre><pre>app.use(bodyParser.urlencoded({ extended: true }))</pre><pre>// parse requests of content-type - application/json</pre><pre>app.use(bodyParser.json())</pre><pre>// Configuring the database</pre><pre>const dbConfig = require(&#39;./config/db.config.js&#39;);</pre><pre>const mongoose = require(&#39;mongoose&#39;);</pre><pre>mongoose.Promise = global.Promise;</pre><pre>// Connecting to the database</pre><pre>mongoose.connect(dbConfig.url, {</pre><pre>useNewUrlParser: true</pre><pre>}).then(() =&gt; {</pre><pre>  console.log(&quot;Successfully connected to the database&quot;);</pre><pre>}).catch(err =&gt; {</pre><pre>  console.log(&#39;Could not connect to the database.&#39;, err);</pre><pre>  process.exit();</pre><pre>});</pre><pre>// define a root/default route</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {</pre><pre>   res.json({&quot;message&quot;: &quot;Hello World&quot;});</pre><pre>});</pre><pre>// listen for requests</pre><pre>app.listen(port, () =&gt; {</pre><pre>   console.log(`Node server is listening on port ${port}`);</pre><pre>});</pre><p>Now we’ll run the web server using nodemon. For that we can run</p><pre>nodemon server.js</pre><p>Even we do not need to add .js extension . Another way is add a line in package.jsonfile then we have can run nodemon start that will auto restart the server when do some changes in code.</p><pre>// package.json file a few line snapshot<br>&quot;scripts&quot;: {</pre><pre>&quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,</pre><pre>&quot;start&quot;:&quot;nodemon server&quot; // add this line</pre><pre>}</pre><p>Now run in terminal</p><pre>nodemon start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*9MKoVtCKiTrGInguZjT4yg.png" /></figure><h4>Create model in Mongoose</h4><p>Now we’ll create model for that we make seperate directory for model, routes and controllers. Now create src/models at the root of project.</p><pre>mkdir -p src/models<br>cd src/models</pre><p>Now, create a file named user.model.js inside src/models folder with the following code -</p><pre>touch src/models/user.model.js</pre><p>Here is user.model.js file code -</p><pre>const mongoose = require(&#39;mongoose&#39;);<br><br>const UserSchema = mongoose.Schema({<br>    first_name: String,<br>    last_name: String,<br>    email: String,<br>    phone: String,<br>    is_active:  { type: Boolean, default: false },<br>    is_verified:  { type: Boolean, default: false },<br>    is_deleted:  { type: Boolean, default: false }<br>}, {<br>    timestamps: true<br>});<br><br>module.exports = mongoose.model(&#39;User&#39;, UserSchema);</pre><p>I have also added a <a href="http://mongoosejs.com/docs/guide.html#timestamps">timestamps</a> option to the schema.</p><p>Mongoose uses this option to automatically add two new fields — createdAt and updatedAt to the schema.</p><h4><strong>Create routes using Express</strong></h4><p>Next we’ll setup the routes for the our APIs. Create a new folder called routes inside the src folder and also create user.routes.js file too inside src/routes directory.</p><pre>mkdir src/routes<br>cd src/routes<br>touch user.routes.js</pre><p>Now user.routes.js look like as</p><pre>const express = require(&#39;express&#39;)</pre><pre>const router = express.Router()</pre><pre>const userController = require(&#39;../controllers/user.controllers&#39;);</pre><pre>// Retrieve all users</pre><pre>router.get(&#39;/&#39;, userController.findAll);</pre><pre>// Create a new user</pre><pre>router.post(&#39;/&#39;, userController.create);</pre><pre>// Retrieve a single user with id</pre><pre>router.get(&#39;/:id&#39;, userController.findOne);</pre><pre>// Update a user with id</pre><pre>router.put(&#39;/:id&#39;, userController.update);</pre><pre>// Delete a user with id</pre><pre>router.delete(&#39;/:id&#39;, userController.delete);<br>module.exports = router</pre><p>Note that We have added a require statement for user.controllers.js file. We’ll define the controller file in the next step. The controller will contain methods for handling all the CRUD operations for our api.</p><p>Before defining the controller, let’s first include the routes in server.js. Add the following require statement before app.listen() line inside server.js file.</p><pre>// ........<br><br>// Require Users routes</pre><pre>const userRoutes = require(&#39;./src/routes/user.routes&#39;)</pre><pre>// using as middleware</pre><pre>app.use(&#39;/api/users&#39;, userRoutes)</pre><pre>// ........</pre><p>When we run the server we’ll get error when access users url api like</p><pre>Error: Cannot find module &#39;../controllers/user.controllers.js&#39;<br>    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)<br>    at Function.Module._load (internal/modules/cjs/loader.js:562:25)<br>    at Module.require (internal/modules/cjs/loader.js:692:17)</pre><p>The error is because we have not created user.controllers.js file yet.</p><p><strong>Create controllers in express</strong></p><p>Next we’ll setup the controllers for the our APIs. Create a new folder called controllers inside the src folder and also create user.controllers.js file too inside src/controllers directory.</p><pre>mkdir src/controllers<br>cd src/controllers<br>touch user.controllers.js</pre><p>Now user.controllers.js file look like as</p><pre>const User = require(&#39;../models/user.model.js&#39;);</pre><pre>// Retrieve and return all users from the database.</pre><pre>exports.findAll = (req, res) =&gt; {</pre><pre>User.find()</pre><pre>  .then(users =&gt; {</pre><pre>  res.send(users);</pre><pre>}).catch(err =&gt; {</pre><pre>  res.status(500).send({</pre><pre>  message: err.message || &quot;Something went wrong while getting list of users.&quot;</pre><pre>});</pre><pre>});</pre><pre>};</pre><pre>// Create and Save a new User</pre><pre>exports.create = (req, res) =&gt; {</pre><pre>// Validate request</pre><pre>if(!req.body) {</pre><pre>  return res.status(400).send({</pre><pre>  message: &quot;Please fill all required field&quot;</pre><pre>});</pre><pre>}</pre><pre>// Create a new User</pre><pre>const user = new User({</pre><pre>  first_name: req.body.first_name,</pre><pre>  last_name: req.body.last_name,</pre><pre>  email: req.body.last_name,</pre><pre>  phone: req.body.last_name</pre><pre>});</pre><pre>// Save user in the database</pre><pre>user.save()</pre><pre>  .then(data =&gt; {</pre><pre>  res.send(data);</pre><pre>}).catch(err =&gt; {</pre><pre>  res.status(500).send({</pre><pre>  message: err.message || &quot;Something went wrong while creating new user.&quot;</pre><pre>});</pre><pre>});</pre><pre>};</pre><pre>// Find a single User with a id</pre><pre>exports.findOne = (req, res) =&gt; {</pre><pre> User.findById(req.params.id)</pre><pre>  .then(user =&gt; {<br>  if(!user) {</pre><pre>   return res.status(404).send({</pre><pre>   message: &quot;User not found with id &quot; + req.params.id</pre><pre> });</pre><pre>}</pre><pre> res.send(user);</pre><pre>}).catch(err =&gt; {</pre><pre>  if(err.kind === &#39;ObjectId&#39;) {</pre><pre>    return res.status(404).send({</pre><pre>    message: &quot;User not found with id &quot; + req.params.id</pre><pre>  });</pre><pre>}</pre><pre>return res.status(500).send({</pre><pre>  message: &quot;Error getting user with id &quot; + req.params.id</pre><pre>});</pre><pre>});</pre><pre>};</pre><pre>// Update a User identified by the id in the request</pre><pre>exports.update = (req, res) =&gt; {</pre><pre>// Validate Request</pre><pre>if(!req.body) {</pre><pre>  return res.status(400).send({</pre><pre>  message: &quot;Please fill all required field&quot;</pre><pre>});</pre><pre>}</pre><pre>// Find user and update it with the request body</pre><pre>User.findByIdAndUpdate(req.params.id, {</pre><pre>  first_name: req.body.first_name,</pre><pre>  last_name: req.body.last_name,</pre><pre>  email: req.body.last_name,</pre><pre>  phone: req.body.last_name</pre><pre>}, {new: true})</pre><pre>.then(user =&gt; {</pre><pre> if(!user) {</pre><pre>   return res.status(404).send({</pre><pre>   message: &quot;user not found with id &quot; + req.params.id</pre><pre> });</pre><pre>}</pre><pre>res.send(user);</pre><pre>}).catch(err =&gt; {</pre><pre>if(err.kind === &#39;ObjectId&#39;) {</pre><pre>  return res.status(404).send({</pre><pre>  message: &quot;user not found with id &quot; + req.params.id</pre><pre>});</pre><pre>}</pre><pre>return res.status(500).send({</pre><pre>  message: &quot;Error updating user with id &quot; + req.params.id</pre><pre>});</pre><pre>});</pre><pre>};</pre><pre>// Delete a User with the specified id in the request</pre><pre>exports.delete = (req, res) =&gt; {</pre><pre>User.findByIdAndRemove(req.params.id)</pre><pre>.then(user =&gt; {</pre><pre>if(!user) {</pre><pre>  return res.status(404).send({</pre><pre>  message: &quot;user not found with id &quot; + req.params.id</pre><pre>});</pre><pre>}</pre><pre>res.send({message: &quot;user deleted successfully!&quot;});</pre><pre>}).catch(err =&gt; {</pre><pre>if(err.kind === &#39;ObjectId&#39; || err.name === &#39;NotFound&#39;) {</pre><pre>  return res.status(404).send({</pre><pre>  message: &quot;user not found with id &quot; + req.params.id</pre><pre>});</pre><pre>}</pre><pre>return res.status(500).send({</pre><pre>  message: &quot;Could not delete user with id &quot; + req.params.id</pre><pre>});</pre><pre>});</pre><pre>};</pre><p>You can check out the documentation of all the methods that we used in the above APIs on Mongoose’s official documentation -</p><ul><li><a href="http://mongoosejs.com/docs/api.html#find_find">Mongoose find()</a></li><li><a href="https://mongoosejs.com/docs/api.html#document_Document-save">Mongoose save()</a></li><li><a href="http://mongoosejs.com/docs/api.html#findbyid_findById">Mongoose findById()</a></li><li><a href="http://mongoosejs.com/docs/api.html#findbyidandupdate_findByIdAndUpdate">Mongoose findByIdAndUpdate()</a></li><li><a href="http://mongoosejs.com/docs/api.html#findbyidandremove_findByIdAndRemove">Mongoose findByIdAndRemove()</a></li></ul><p><strong>API end points</strong></p><ol><li>GET /api/users: will give all users stored in database</li><li>GET /api/users/&lt;user_id&gt;: will give a specific user with user_id.</li><li>POST /api/users : user can create a new user</li><li>PATCH /api/users/&lt;user_id&gt;: update a user partially</li><li>DELETE /api/users/&lt;user_id&gt;: delete a user</li><li>PUT /api/users/&lt;user_id&gt;: update a user completely</li></ol><p><strong>Now Time to set APIs in post</strong></p><p>Creating a new user api/users using POST method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*3UYdxUWc65S8I0bugklD1A.png" /></figure><p>Get all users list /api/users using GET method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*t4xOqGvSTdxIFGMGm-Gilg.png" /></figure><p>Get user by specific id api/users/user_id using GET method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*yp-9igslWPREr2_Xi6lkJw.png" /></figure><p>Update user by specific id api/users/user_id using PUT method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*uU-jZDD3NXDz4f9BuvbjwQ.png" /></figure><p>Delete user by specific id api/users/user_id using DELETE method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*upyWqnqOX8VvmtZkQiRVWA.png" /></figure><h4><strong>Conclusion</strong></h4><p>In this story, we had learnt how to make APIs using Node, Express and MongoDB.</p><p>You can find <a href="https://github.com/rahulguptafullstack/NodeJsExpressApi">here git repository</a>.</p><pre><a href="https://github.com/rahulguptafullstack/NodeJsExpressApi">https://github.com/rahulguptafullstack/NodeJsExpressApi</a></pre><p>Thanks for reading. Hope it helps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d25a0e27937" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>