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

in #utopian-io6 years ago (edited)

Image Source

Repository   

https://github.com/nodejs/node

What Will I Learn? 

I will learn how to add routes to our project using the GET, POST , PATCH and DELETE requests .

  • How to add routes to the sponsors ( Get, Post, Patch and Delete )
  • How to add routes to the contributions (Get , Post )
  • How to restart the server automatically with nodemon package .

Requirements  

  • Knowledge about JavaScript language .
  • Basic Knowledge about Command Line window .
  • An editor for example notepad ++ .

Difficulty   

  • Basic

Tutorial Contents

In this tutorial we will learn how to create a rest api with Node  Js , in the previous tutorial we have created only one route (one URL) , and today we will create other routes , so let's start .. 

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 .

By the cmd I have created the ' api ' folder inside the nodeRestUtopian folder which is our project .

By the cd api I have entered inside the API folder and I created another folder named ' routes ' by mkdir routes  that means ' make directory with the name routes ' , and this is the result : 

In my API folder I have the routes folder , I have created also a JS file ' sponsors.js ' , why I created this file ? 

Simply because the plan of my project is to build a REST API with sponsors and Contributions and this is the plan : 

As I mentioned in the last tutorial 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 ?

Firstly we import the express framework by declaring a varibale and using the ' require ' code 

var express = require('express');

After that I need to create an instance of the express  ' Router() ' with capital R , it will give us the permission  to determining how your application responds to a client request.

var router = express.Router();

By this instance we can use the method get('/...') to handle a coming get request from the client , the method get has two parameters :

  1. The first is the URL or the resource .
  2. The second is the function .

There is two different solutions , the first is to keep the URL like router.get('/sponsors') , but if we have many routes for example I propose to let the URL like router.get('/'); just a ' / ' that means all the requests targeting anything with the '/sponsors ' will be redirect to the sponsors.js file .

I think it was a little difficult to understand , let's do an example to clarify the idea .

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 

var sponsorsR = require('./api/routes/sponsors');

This is our route without .js in the end , now when the request is targeting to /sponsors , let's see what happens ..

app.use('/sponsors', sponsorsR);

By the variable app I used the method 'use' this method has two parameters , when the user  requests the sponsors page he will be forwareded to the sponsors.js file by this route './api/routes/sponsors ' .

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 router.get('/'); and now I can explain to you why I used only the '/' not '/sponsors' as parameter to the get method .

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 router.get('/sponsors') it will be '/sponsors/sponsors/' but if we let '/' it will be '/sponsors' .

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 

router.get('/', function(req, res){

res.status(200).json({

message : "Get request to /sponsors"

});

});

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 ! 

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 

I have my sposorsR variable which require the route and I have used the ' use ' method .

Now let's start the our server which listen to the port 3000 ..

I will test it by the Postman localhost:3000/ is our localhost and this is the result 

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 ?

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 .

router.post('/', function(req, res){

res.status(200).json({

message : "Post request to /sponsors"

});

});

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 .

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 router.get('/:idS'); and inside the function we create a variable to get the id var id = req.params.idS; ,then we check if the id for example == to ' 0 ' we return a message , this is the full code :

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 :

The message is the best sponsor and the id is 0 , it works ! , and if we enter another id this is the result 

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 ?

router.patch('/idS'); 

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 :

router.patch('/:idS', function(req, res){

var id = req.params.idS;

res.status(200).json({

message : "This sponsor "+ id + " was updated"

});

});

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

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 

router.delete('/:idS', function(req, res){

var id = req.params.idS;

res.status(200).json({

message : "This sponsor "+ id + " was deleted"

});

});

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 ,  now let's do the same thing for the contributions , we need POST and GET verbs ..

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 

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 .

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 ' .

There is a problem , every time I restart the server to get the new changes , but what if I forget it ? 

The solution : 

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 npm install nodemon --save-dev , and to understand what means this code just read this tutorial .

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 .

This is the result when I send a get request with a specific ID 

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 ..

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 

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 .

This is the package.JSON file , inside the scripts object we have the start attribute with the 'nodemon serverUtopian.js ' value , just we type npm start in the CMD and this is the result : 

It will be automatically , if you want to know more about this package just type nodemon -h it will give you more informations about using this package .

In order to fully understand the terms that I have used, you  should read past tutorials in which I have provided all about Node JS  and Node Package Manager .

Curriculum 

Proof of Work Done 

https://github.com/alexendre-maxim/routesUtopian

Sort:  

Thank you for your contribution.
While I liked the content of your contribution, I would still like to extend few advices for your upcoming contributions:

  • Resources: Put more links on the tools and technologies you use.
  • Structure of the tutorial: Improve the structure of your tutorial so that it is easier to read. An example of a good tutorial link.

Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Fool me once, shame on you. Fool espoem once and he will roundhouse kick you in the face.

Thank you sir , I will add a resources in my next tutorial

Hey @alexendre-maxim
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.033
BTC 62891.03
ETH 3103.58
USDT 1.00
SBD 3.89