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

Image for post
Image for post

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.

Image for post
Image for post

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.

Image for post
Image for post

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.

Image for post
Image for post
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.

Image for post
Image for post
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.

Image for post
Image for post

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.

Image for post
Image for post

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

Image for post
Image for post
productRoutes.js
Image for post
Image for post

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()
Image for post
Image for post

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.

Image for post
Image for post

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

Image for post
Image for post

The path taken by the request is illustrated below:

Image for post
Image for post

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.
Image for post
Image for post

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.

Image for post
Image for post

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.

Image for post
Image for post

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.

Image for post
Image for post
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.

Image for post
Image for post

voilà , we received the expected output.👏👏

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

Full stack developer, Sitarist

Get the Medium app