Node Js Tutorial Creating a REST API #02 Adding Routes To The API And Use The Nodemon Package

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@alexendre-maxim·
0.000 HBD
Node Js Tutorial Creating a REST API #02 Adding Routes To The API And Use The Nodemon Package
<html>
<p><img src="https://steemitimages.com/0x0/https://cdn-images-1.medium.com/max/1146/1*vBw9_VPFiEcxgxDx-Oghzw.png" width="1146" height="328"/></p>
<p><a href="https://steemitimages.com/0x0/https://cdn-images-1.medium.com/max/1146/1*vBw9_VPFiEcxgxDx-Oghzw.png">Image Source</a></p>
<h2>Repository &nbsp;&nbsp;</h2>
<p>https://github.com/nodejs/node</p>
<h2>What Will I Learn?&nbsp;</h2>
<p>I will learn how to add routes to our project using the GET, POST , PATCH and DELETE requests .</p>
<ul>
  <li>How to add routes to the sponsors ( Get, Post, Patch and Delete )</li>
  <li>How to add routes to the contributions (Get , Post )</li>
  <li>How to restart the server automatically with nodemon package .</li>
</ul>
<h2>Requirements &nbsp;</h2>
<ul>
  <li>Knowledge about JavaScript language .</li>
  <li>Basic Knowledge about Command Line window .</li>
  <li>An editor for example notepad ++ .</li>
</ul>
<h2>Difficulty &nbsp;&nbsp;</h2>
<ul>
  <li>Basic</li>
</ul>
<h2>Tutorial Contents</h2>
<p>In this tutorial we will learn how to create a rest api with Node &nbsp;Js , in the previous tutorial we have created only one route (one URL) , and today we will create other routes , so let's start ..&nbsp;</p>
<p>Let's create the API but firstly we must create the folder routes to organize the project and to use the URL of each route .</p>
<p><img src="https://e.top4top.net/p_901yue3k1.png" width="617" height="107"/></p>
<p>By the cmd I have created the ' api ' folder inside the nodeRestUtopian folder which is our project .</p>
<p><img src="https://f.top4top.net/p_901khpoe2.png" width="926" height="116"/></p>
<p>By the <code>cd api</code> I have entered inside the API folder and I created another folder named ' routes ' by <code>mkdir routes </code>&nbsp;that means ' make directory with the name routes ' , and this is the result :&nbsp;</p>
<p><img src="https://c.top4top.net/p_9019awiu1.png" width="799" height="290"/></p>
<p>In my API folder I have the routes folder , I have created also a JS file ' sponsors.js ' , why I created this file ?&nbsp;</p>
<p>Simply because the plan of my project is to build a REST API with sponsors and Contributions and this is the plan :&nbsp;</p>
<p><img src="https://steemitimages.com/0x0/https://d.top4top.net/p_852vga081.jpg" width="600" height="440"/></p>
<p>As I mentioned in <a href="https://steemit.com/utopian-io/@alexendre-maxim/node-js-tutorial-creating-a-rest-api-01-what-s-the-api-and-how-to-build-it">the last tutorial </a>we will generate the ' GET , Post and Patch id ' Verbs , so the ' /sponsors ' will be the resource or the URL , for the PATCH if we have the link /sponsors/3 for example in this format /sponsors/{id} it will give you the specific sponsor , the question is how to do that ?</p>
<p>Firstly we import the express framework by declaring a varibale and using the ' require ' code&nbsp;</p>
<p><code>var express = require('express');</code></p>
<p>After that I need to create an instance of the express &nbsp;' Router() ' with capital R , it will give us the permission &nbsp;to determining how your application responds to a client request.</p>
<p><code>var router = express.Router();</code></p>
<p>By this instance we can use the method <code>get('/...') </code>to handle a coming get request from the client , the method get has two parameters :</p>
<ol>
  <li>The first is the URL or the resource .</li>
  <li>The second is the function .</li>
</ol>
<p>There is two different solutions , the first is to keep the URL like <code>router.get('/sponsors') </code>, but if we have many routes for example I propose to let the URL like <code>router.get('/');</code> just a ' / ' that means all the requests targeting anything with the '/sponsors ' will be redirect to the sponsors.js file .</p>
<p>I think it was a little difficult to understand , let's do an example to clarify the idea .</p>
<p>Firstly let's import our sopnsors route and make it inside a variable named for example sponsorsR by the require we just write the URL of our route&nbsp;</p>
<p><code>var sponsorsR = require('./api/routes/sponsors');</code></p>
<p>This is our route without .js in the end , now when the request is targeting to /sponsors , let's see what happens ..</p>
<p><code>app.use('/sponsors', sponsorsR);</code></p>
<p>By the variable app I used the method 'use' this method has two parameters , when the user &nbsp;requests the sponsors page he will be forwareded to the sponsors.js file by this route './api/routes/sponsors ' .</p>
<p>So the first parameter is the URL that the user requests , and the second is the route , and when we return to the sponsors.js file we have the method <code>router.get('/');</code> and now I can explain to you why I used only the '/' not '/sponsors' as parameter to the get method .</p>
<p>When the user requests the sponsors page it will enter /sponsors , the system will redirect the user to the sponsors by the verbs that he requested , now the URL has '/sponsors ' if we write <code>router.get('/sponsors')</code> it will be '/sponsors/sponsors/' but if we let '/' it will be '/sponsors' .</p>
<p>The method router.get('/') has another parameter which is a function , this function actually has two parameters , the request and the response , I will use the response to send a JSON response with a message and this is the code&nbsp;</p>
<p><code>router.get('/', function(req, res){</code></p>
<p><code>res.status(200).json({</code></p>
<p><code>message : "Get request to /sponsors"</code></p>
<p><code>});</code></p>
<p><code>});</code></p>
<p>The status is (200 ok ) as I explained in the previous tutorial , the response with the method .json has the attribute message with the value = get request to sponsors , it's just a message you can write anything just to test if the get request works or no !&nbsp;</p>
<p><img src="https://d.top4top.net/p_90112s152.png" width="658" height="301"/></p>
<p>This is the sponsors.js file and this is the message in the get request , we have two variables as I mentioned above , by the response I sent a message and this is the app.js file&nbsp;</p>
<p><img src="https://c.top4top.net/p_901j8zcm1.png" width="841" height="294"/></p>
<p>I have my sposorsR variable which require the route and I have used the ' use ' method .</p>
<p>Now let's start the our server which listen to the port 3000 ..</p>
<p><img src="https://a.top4top.net/p_901efstc5.png" width="521" height="36"/></p>
<p>I will test it by the Postman <code>localhost:3000/</code> is our localhost and this is the result&nbsp;</p>
<p><img src="https://f.top4top.net/p_901d7v9k4.png" width="1366" height="685"/></p>
<p>The Postman gives us an error because there is no page in this route localhost:3000 , but what do you think if we write localhost:3000/sponsors ? with the get request ?</p>
<p><img src="https://e.top4top.net/p_9018mqd23.png" width="1366" height="685"/></p>
<p>Great ! our message was appeared , you can sure replace the message by the page that you want or anything , but if we chose ' post ' it will give an error why ? because we added just the get so let's add the post request .</p>
<p><code>router.post('/', function(req, res){</code></p>
<p><code>res.status(200).json({</code></p>
<p><code>message : "Post request to /sponsors"</code></p>
<p><code>});</code></p>
<p><code>});</code></p>
<p>This is the code so I used the post method with the same parameters , and I just changed the message to see the difference between the post and get .</p>
<p><img src="https://b.top4top.net/p_901kwdrk1.png" width="1366" height="686"/></p>
<p>Now we have generated the post and get requests , I need to get a specific sponsor by id for example and to do that we need a variable inside the get request <code>router.get('/:idS'); </code>and inside the function we create a variable to get the id <code>var id = req.params.idS; </code>,then we check if the id for example == to ' 0 ' we return a message , this is the full code :</p>
<p><img src="https://d.top4top.net/p_901g1xgf1.png" width="802" height="689"/></p>
<p>And I checked if the id equals to 0 so this is the best sponsor else if the id is not equals to 0 it's normal sponsor and this is the result :</p>
<p><img src="https://e.top4top.net/p_901m8d4n2.png" width="1366" height="686"/></p>
<p>The message is the best sponsor and the id is 0 , it works ! , and if we enter another id this is the result&nbsp;</p>
<p><img src="https://f.top4top.net/p_901msz9z3.png" width="1366" height="683"/></p>
<p>We have completed the get , post and get with a special id , now I want to add a PATCH request to update a sponsor and a DELETE request to delete also a sponsor , how to do it ?</p>
<p><code>router.patch('/idS');&nbsp;</code></p>
<p>We specify the id of the sponsor to update and we send the request , then I will just test by a message , this is the full code :</p>
<p><code>router.patch('/:idS', function(req, res){</code></p>
<p><code>var id = req.params.idS;</code></p>
<p><code>res.status(200).json({</code></p>
<p><code>message : "This sponsor "+ id + " was updated"</code></p>
<p><code>});</code></p>
<p><code>});</code></p>
<p>I specify the id and I just send a message that the sponsor with this id was updated and this is the result from Postman</p>
<p><img src="https://d.top4top.net/p_9011yoth1.png" width="1366" height="689"/></p>
<p>I need to delete a sponsor for example and to do that I need a delete request with the id and this is the code&nbsp;</p>
<p><code>router.delete('/:idS', function(req, res){</code></p>
<p><code>var id = req.params.idS;</code></p>
<p><code>res.status(200).json({</code></p>
<p><code>message : "This sponsor "+ id + " was deleted"</code></p>
<p><code>});</code></p>
<p><code>});</code></p>
<p>The same format I sepecified the id of the sponsor and I send the message the sponsor was deleted with the id that the user entered , &nbsp;now let's do the same thing for the contributions , we need POST and GET verbs ..</p>
<p><img src="https://a.top4top.net/p_9019pcpn1.png" width="592" height="341"/></p>
<p>This is the full code from the contributions.js file , the same codes in get , post requests I just changed the message , and this is the app.js file&nbsp;</p>
<p><img src="https://b.top4top.net/p_901clle92.png" width="584" height="212"/></p>
<p>I added the contributionsR variable that's require the contributions.js route then I have used the method ' use ' to check if the URL is ' /contributions ' then redirect me to the contributions file .</p>
<p><img src="https://c.top4top.net/p_901ihhfl3.png" width="1366" height="509"/></p>
<p>And this is the result from the postman , sure after restart the server and write the /contributions it will apply the get method and this is the message 'List of contributions ' .</p>
<p>There is a problem , every time I restart the server to get the new changes , but what if I forget it ?&nbsp;</p>
<h3>The solution :&nbsp;</h3>
<p>We have a package called nodemon , this package will save and restart the server with every change it gets , to install it go to the CMD and type <code>npm install nodemon --save-dev </code>, and to understand what means this code just <a href="https://steemit.com/utopian-io/@alexendre-maxim/node-package-manager-tutorial-how-to-install-and-uninstall-global-and-local-packages-and-how-to-list-them">read this tutorial</a> .</p>
<p><img src="https://a.top4top.net/p_902foh1v1.png" width="960" height="252"/></p>
<p>So the nodemon now is available in my project , I have installed it like a dev dependency because we need this version to develop , and now to start the server we don't need the manual method just type ' nodemon serverUtopian.js ' once , it will restart automatically .</p>
<p><img src="https://f.top4top.net/p_902yt7271.png" width="510" height="91"/></p>
<p>This is the result when I send a get request with a specific ID&nbsp;</p>
<p><img src="https://e.top4top.net/p_902dozgj1.png" width="1366" height="556"/></p>
<p>And now I will try to change something in my code , save it and directly send a request without restarting the server to check if the nodemon really restart automatically the server or no ..</p>
<p><img src="https://f.top4top.net/p_902a8oiu2.png" width="528" height="139"/></p>
<p>I just changed the message I added the word ' the ' and I have saved it , let's send a request without restarting the server and see the result&nbsp;</p>
<p><img src="https://a.top4top.net/p_902wzjl13.png" width="1366" height="537"/></p>
<p>the nodemon is already works , there is another method is to add the ' nodemon serverUtopian.js ' inside a script and with the command npm ' name script ' it will start automatically .</p>
<p><img src="https://c.top4top.net/p_902zfae21.png" width="828" height="401"/></p>
<p>This is the package.JSON file , inside the scripts object we have the start attribute with the<code> 'nodemon serverUtopian.js '</code> value , just we type <code>npm start</code> in the CMD and this is the result :&nbsp;</p>
<p><img src="https://d.top4top.net/p_902oou532.png" width="600" height="154"/></p>
<p>It will be automatically , if you want to know more about this package just type <code>nodemon -h </code>it will give you more informations about using this package .</p>
<p><img src="https://e.top4top.net/p_902wiuln1.png" width="697" height="482"/></p>
<h4>In order to fully understand the terms that I have used, you &nbsp;should read past tutorials in which I have provided all about Node JS &nbsp;and Node Package Manager .</h4>
<h2>Curriculum&nbsp;</h2>
<ul>
  <li><a href="https://steemit.com/utopian-io/@alexendre-maxim/node-js-tutorial-creating-a-rest-api-01-what-s-the-api-and-how-to-build-it">&nbsp;Node Js Tutorial Creating a REST API #01 What's the API and How To Build It&nbsp;</a></li>
  <li>&nbsp;<a href="https://steemit.com/utopian-io/@alexendre-maxim/node-package-manager-tutorial-what-s-the-semantic-versioning-and-how-to-control-it-also-from-the-package-json-file">Node Package Manager Tutorial What's The Semantic Versioning And How To Control It Also From The Package.Json File</a></li>
  <li>&nbsp;<a href="https://steemit.com/utopian-io/@alexendre-maxim/node-package-manager-tutorial-how-to-install-and-uninstall-global-and-local-packages-and-how-to-list-them">Node Package Manager Tutorial How To Install And Uninstall Global And Local Packages And How To List Them</a></li>
  <li><a href="https://steemit.com/utopian-io/@alexendre-maxim/node-package-manager-tutorial-how-to-get-the-npm-and-how-to-create-the-package-json">&nbsp;Node Package Manager Tutorial How To Get The NPM and How To Create The Package.JSON</a></li>
  <li>&nbsp;<a href="https://steemit.com/utopian-io/@alexendre-maxim/node-js-tutorial-select-from-where-order-by-delete-and-limit-using-mysql-module">Node Js Tutorial Select From Where , Order by , Delete and Limit Using Mysql Module</a></li>
  <li><a href="https://steemit.com/utopian-io/@alexendre-maxim/node-js-tutorial-serve-html-pages-serve-json-data-connect-and-insert-into-db-using-mysql-module">&nbsp;Node Js Tutorial Serve HTML Pages , Serve JSON Data , Connect And Insert Into DB Using Mysql Module</a></li>
  <li><a href="https://steemit.com/utopian-io/@alexendre-maxim/node-js-tutorial-how-to-create-read-and-write-stream-manually-and-automatically-for-big-files">Node Js Tutorial How To Create Read And Write Stream Manually And Automatically For Big Files</a></li>
  <li><a href="https://steemit.com/utopian-io/@alexendre-maxim/node-js-tutorial-read-write-and-edit-files-and-directories-by-fs-module">Node Js Tutorial Read , Write and Edit files and directories by fs module</a></li>
  <li><a href="https://steemit.com/utopian-io/@alexendre-maxim/node-js-tutorial-how-to-use-event-emitter-by-events-module">Node JS Tutorial How To Use Event Emitter By Events Module</a></li>
</ul>
<h2>Proof of Work Done&nbsp;</h2>
<p>https://github.com/alexendre-maxim/routesUtopian</p>
</html>
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,