googleads
Build A Node.js API In 30 Minutes | Hire MEAN Stack Developers
preloder
API Node.js Web Development

Build A Node.js API In 30 Minutes

The purpose of this blog is to guide you through writing a basic nodejs CRUD (CREATE, READ, UPDATE, DELETE) API which you can use as a foundation for any of your application.

Though there are many nodejs frameworks like Hapi, Sails, I wrote these Node.js API with express framework, because it is very simple and enable us to write very minimal code by providing support for routing, middleware and thereby giving much flexibility than other frameworks.

Before getting started with writing Node.js API make sure you have installed the latest version of node using below command,

Also, we require npm (node package manager) to be installed through which we can install modules that are used in the API.

node -v and npm -v will show the version of NODE and NPM installed on your machine

We’re using Mongo database here. Refer to the official MongoDB installation manual and Install mongo DB based on your OS and version. You can check your installed MongoDB version using mongo –version.

Then, create a database in MongoDB with the name of your choice. I named it as notes_blog.

Here in this example, I created an application to add, display, update and delete notes. To start with the application.

Create a folder named manage_notes. Locate the folder in the terminal and give npm init. This will prompt you with many questions. Press enter for all the questions, and it will initialize your application with the package.json file.

Paste the below code into the package.json and save it. In the terminal run “npm install.” This will install the packages defined in the dependencies section of package.json to the project.

 

Also Read: Setup Node.js, Nginx And MongoDB On Ubuntu 16.04

Create a folder named “DB” in the root of the application and again create a file with the following content inside that folder. This file would hold the code to connect to mongo database. Paste the following code in mongoose.js.

Here the Mongoose module is used to interact with the database. Mongoose connect method is used to establish the connection to the mongo database.

Let’s create a starting point for our application, by creating a file named server.js in the root folder of the application and paste the following code.

 

Related: How To Interact With Database Using Async Module In Node.js

First, express and body-parser modules are imported. bodyParser.json(), bodyParser.urlencoded() are middlewares of body-prser module that have access to request objects, transform them and exposes it to the req.body object which then can be accessed in our routes. Then, initialize your app as an instance of the Express framework, and add the body-parser middleware using express’s app.use() method. I also required the “connect_mongo.js” file to establish a connection to DB before listening to the port. Then i made the app to listen to the port 3000 using app.listen() function.

[ctt template=”12″ link=”L0qHD” via=”no” ]In spite of writing all code in a single file, I am going to split it into multiple files, following MVC design pattern which helps in readability of the code and helps to handle better when the size of the application grows in future.[/ctt]

Here M stands for model, which holds function code related to the database. V stands for the view which is beyond the scope of this blog. C for the controller which acts as the intermediator between view and model and also accepts the incoming request, and in turn call the corresponding model function based on the request, process it and sends the response back to the view. Here there is an additional route files inside the folder called routes, which resolve the requested URL from view to a particular controller.

Create another file named notes.model.js inside a newly created folder called to model and paste the following code,


// A function to fetch particular note from the notes collection based on the Id

// A function to save a note to the notes collection

// A function to update a note with note_id

// A function to delete a note from notes collection with node_id

Mongoose module is again required in this file and then, defined the structure of how our notes collection should look like. This notes collection contain two fields title and description with datatype as a string. All the functions that saves, lists, update, delete notes to mongo database are also written in this file.

Create a file named notes.controller.js inside a newly created folder called controller with the following code.

Finally to define the routes for application, create a file named notes.route.js inside a newly created folder called routes with the following code.

This file required the controller file (notes.controller.js) which we defined before.
Remember to include this notes.route.js file in server.js before the app.listen() function. Based on the URL request from the client side, the route is matched, and corresponding controller method is called from here which in turn will call the respective model function, and the response is returned back to the client.

At the end, your folder structure should be like this,

manage_notes
    node_modules
    package.json
    server.js
    db
      connect_mongo.js
   controller
       notes.controller.js
    models
        notes.model.js
    routes
        notes.route.js

Save all the files and locate the application folder in terminal and enter “npm start.” Now you can see server listening to the port 3000(as mentioned in the server.js file). To test the api’s, we use an application called postman from where the HTTP request can be made with request or query or body parameters.

Testing the API’s In postman,

 

Saving A Note:

Display A Note By Id:

Display All Notes:

Update A Note:

Delete A Note:

Thats all! Now keep this as a base, apply this CRUD operations and start creating your own Node.JS API.

Similarly you can learn more on latest topics, never miss out anything from  our largest blog portal where you can get continuous blog updates & latest posts about all latest technologies which would be perfect for your 15 minutes tea break! In case if you’re a newbie then don’t forget to subscribe us to get the latest updates from diverse technologies. What else guys hit the  subscribe link  and go crazy over learning. For more inquires reach us via info@agiratech.com

The following two tabs change content below.

Ramya Venkatesan

Junior Software Engineer discovered her passion in Software engineering and getting specialized in developing Node.Js & Angular applications. Chill out! Coz, this super cool girl hate to be serious as she always thrives to live her life like a gambling game.

One thought on “Build A Node.js API In 30 Minutes”

Leave a Reply

Your email address will not be published. Required fields are marked *

[contact-form-7 id="120788" title="Web Page Form"]

Schedule Your Call