Part 02_Build a RESTful API using Node.js Express , MongoDB and JWT for authorization for BeginnersšŸš€šŸš€

renuja de costa
7 min readDec 3, 2020

In the previous article , we have talked about basic routing with an introduction to express.js, postman.

Plan it and Build it

Now that we have covered a lot of the basics, its time to build our REST API.

This is what our REST API is going to look like. You could have an idea of all the routes that are included in the REST API that we are going to include in our API from the above diagram.

  1. localhost:3000/ targets to the root URL
  2. localhost:3000/products targets to the products resource and it consists of two types of requests which are GET and POST. The GET request to the products resource returns products and POST request allows to create a products resource.
  3. localhost:3000/products/:id targets an individual product and has three types of requests which are GET, PATCH and DELETE.

Lets try to implement this in our code. Before that lets see what we have already on our server.js file.

From what we have right now, we could only target the root URL which is of request type GET .

Now we ā€˜ll add the GET and POST requests for the /products routes and the /user routes to our code.

server.js file

As you can see the server.js gets a bit messy and becomes even more harder to maintain if we keep on adding all the routes to one file itself. So for simplicity it is much more better to maintain the user routes and product routes on different files separately and makes the code more readable and maintainable rather than packing everything on one file.

folder structure

Weā€™ll be adding all the product routes to the productRoutes.js file and the user routes to the userRoutes.js file.

Before we get into classifying the code in the server.js file into the files productRoutes.js and userRoutes.js , ( although we have discussed about basic routing on the part 1 of this tutorial) we need to know more about routing, writing middleware and how to use middleware.

Middleware

Although we havenā€™t talked about middleware, weā€™ve been using it from the get-go of our server.js file.

Middleware is basically anything that happens between the time the server receives the request and sends the response.

Therefore all the app.METHOD functions that we have used with the route handlers are basically middleware functions.

But thereā€™s another way of writing middleware to our application.And thatā€™s by using the app.use()method.

You could read more about middleware on the official express.js website and please do so as we are only covering the basics needed to get the REST API up and running.

So far the middleware we have used have been implemented in an application level i.e. we have created an instance of express by the app object by using app.METHOD() for now and later weā€™ll also be using app.use()

But we could also implement middleware using Router-level middleware.

Router-level middleware works in the same way as application-level middleware except that it is bounded to an instance of express.Router()

const router = express.Router();

Again , I highly recommend you to read the official documentation for application-level and router-level middleware and the links are given below.

All these will make more sense once we apply these on our REST API. Now lets see how we could use all the theories that we have learnt above.

This is how our new server.js file looks like after being re-organized.

  1. app.use('/products', productRoutes) is passed two arguments. The first one is the route that gets matched. If the route is matched , then the rest is taken care by whatever is inside the productRoutes.js file which is the second argument.

This could be elaborated further with the following examples.

Both the above requests are GET requests that get handled by the productRoutes. So it is clear that the /products route is matched first using the middleware function app.use()and sent to the productsRoutes.js file to determine how the rest of the URL ( /:id & / in this case) has to be handled.

Now let us see what we have on the productRoutes.js file

productRoutes.js

In the productRoutes.js file above, we have taken care of the given endpoints on the right.

Be patient!! I know thereā€™s a lot of new stuff in the productRoutes.js file but weā€™ll be going through each and everyone of them.

Iā€™ve mentioned above that thereā€™s two ways of implementing middleware.

  1. app.use() and app.METHOD()_on the server.js file weā€™ve implemented application-level middleware by binding app to an instance of express()
  2. router.use() and router.METHOD() _ on the productRoutes.js file weā€™ve implemented router-level middleware by binding router to an instance of express.Router()

Now that weā€™ve understood how we implemented middleware on our productRoutes.js file we could continue with the tutorial.

But still some of you might be confused with how all these work. We could do one final thing to understand everything. Weā€™ll make a request and see how the URL reaches its endpoints from the very beginning of its journey.

Request reaching its endpoint

Everything starts from making a request to the preferred endpoint.

And ends with a certain response which is a JSON reponse in this case as follows:

The path taken by the request is illustrated below:

The portion in RED is handled by the server.js file and the GREEN portion of the URL is handled in the productRoutes.js file.

Hopefully you have to have an understanding of the following by now:

  1. implementation of middleware using router-level middleware and application-level middleware.
  2. How the request sent reaches endpoints through the specific routes.

If we take our attention to this POST route , we actually want to create a resource inside the handler of router.post()

In order to get this done, we need to send data through the request and get access to the data in the request sent.

Lets see how we get the above two tasks accomplished.

How do we send data through the request ?

In order to send data through the client we use the request body. Using postman , we could easily get this done as given below.

Before sending the POST request to the /products endpoint, we select Body , raw and select the preferred type of format we want to send data. In this case , JSON is selected and the required data to be sent is typed below in JSON format. Once we click SEND , the request object gets sent with the request body to our API.

Now our API must have a way to identify that the request object being sent is a JSON object. For this we use express.json().

express.json() is a method inbuilt in express to recognize the incoming Request Object as a JSON Object. This method is called as a middleware in your application using : app.use(express.json());

Weā€™ll add this piece of middleware on our server.js file as follows.

How do we access this data?

After our URL gets routed to the productRoutes.js file we need to have access to this data to be sent to the database. Since we havenā€™t dealt with the databases yet, instead Iā€™ll send the JSON object as a response back to our client to prove that we have gained access to the JSON data.

productRoutes.js

As seen above we modify the body of the handler function of router.post()

Using req.body we access the JSON object that is directed to the route and then assign it to variables name , Price using destructuring assignment in javascript.

Now if we send a request to http://localhost:3000/products route with the request data on the body of the request object which is of http request method type POST, we should get the data sent as a response.

voilĆ  , we received the expected output.šŸ‘šŸ‘

If you do not know about the http response status codes ,checkout the link below.

--

--