Node.js development has seen considerable demand, with early adopters, including PayPal and LinkedIn as well as other tech firms that have seen exponential growth in usage. Netflix, in fact, is the best example who leverages Node.js benefits through implementing it in production.What does REST Mean?
Representational State Transfer or Rest. It’s a web standard architecture as well as an HTTP protocol. The architectural style of REST describes six restrictions that originally were communicated by Roy Fielding in the doctoral dissertation, defining the RESTful-style basis as:
- Uniform interface
- Layered system
- (optional) Code on demand
RESTful applications make use of HTTP requests to do four operations, named as CRUD or Create, Read, Update, and Delete. Create and/or delete is used in posting data, get is to read/list data, and delete for removing data. Moreover, RESTful is composed of several methods, including URL, media types, base URL, and others.
The following tutorial will help you learn how to build a RESTful API with Node.js. Here are the following tools:
- A text editor (Sublime, Atom, etc.)
If you are not familiar with Node.js, Express.js or MongtoDB, taking the below courses is highly recommended:
We’ll be creating a RESTful API.
Let’s presume that there is an environment set up already, like MongoDB and Node.js installed.
Run the npm -v and mongo –version, since this would reveal the NPM and the installed MongoDB version on your machine as well.
Open the terminal and follow these:
1. Create a todoListApi - mkdir todo list API folder
2. Navigate to the root of the folder created – cd todo list API
3. Create the package.json file – npm init
Package.son is a file that provides important information to npm, which allows determining a project as well as handling the dependencies. You will be prompted by the npm init to enter few information, like the application’s name and its version, the description, author, and the keyword. Moreover, it will also ask you if you like what you’re seeing.
Eventually, you will have something similar to this.
Type yes and then press
“enter” to complete the package.json. Having done these, the structure of the
folder should be like this:
4. Make a call server.js
–touch server.js file. On the server, we would write protocols to make our
5. Make a folder, API – mkdir API. Create separate folders within the API folder, label them as model, routes, and controllers, by running mkdir API/controllers API/model and API/routes.
6. Build a
todoListController.js in your API/controller folder, the todoListRoutes.js in
your routes folder and the todoListModel in the model folder – touch
Now, the folder structure
should look like this:
Let us install the express and nodemon. To build the server, Express will be used. Nodemon, on the other hand, helps keep track of changes to an application by watching the files changed and restarting the server automatically.
The package.json file, upon successful installation, would be modified to have a couple of newly installed packages.
1. Open package.json file, add the task to script
2. Open the file, server.jsthen type/copy this code.
3. Run npm on the terminal
and run start this with begin the server and you’d see
The first thing to do is to install mongoose -
Why use Mongoose? This is
what we would use for a MongoDB (Database) interaction. After installing, open
the todoListModel.js file I the folder, API/models, and type code to the file
Mongoose is required from the code above in the file. We then create a model of what the collection should look like.
Setting up Routes
Routing means to determine how an application will respond to a client request for a specific endpoint, which is the URL or path of a certain HTTP request method, such as POST, GET, and so on. Each of the routes had various route handler functions executed when a route was matched.
We have defined below a couple of basic routes (‘/tasks’, and ‘/tasks/taskld’) with various methods.
‘/tasks’ has a couple of methods, the GET and the POST, while ‘tasks/taskld’ has GET, PUT, and DELETE.Controller is required so each of the route methods could call the respective handler function.
To do this, open the todoListRoutes.js file in the route folder then paste the following into it
Open the todoListController.js file with the text editor, such as Atom, Sublime, and others, and let’s dig deep into coding.
We’d be writing different functions in the controller, including list_all_tasks, create_a_task, read_a_task, update_a_task, and delete_a_task. Each of the functions we will export to use in our routes
The functions utilize the different methods of mongoose, such as find, findByid, findOneAndUpdate, save, remove.
We had earlier a minimal code to get the server up and running in server.js. We would be connecting handlers or controllers, the models created, the database, the body-parser as well as the routes created together.
Open the server.js file we made and follow these steps to put together everything. Essentially, you’ll be replacing the server.js code with the snippet code in this section.
- Connect the database through adding to the connection a URL mongoose instance.
- Load the model created – task.
- Install the body-parser and use the incoming request bodies in the middleware.
- Register on the server the routes created
- Begin the MongoDB server. Open the terminal, run mongod which commences the MongoDB server. You could restart the node server once the MongoDB server is running by running on a nodemon terminal.
Testing through Postman
Now that everything’s been connected, we’ll test each route and their respective methods.
Since there’s nothing in the database yet, on entering you should see this: “”.
2. On the same address, change the method to POST and then click the body and choose “x-www.form-urlencoded”. Enter the name as key and the corresponding name enter as value. After, click on the send button, which should give you a 200 ok response.
What happens should we enter the wrong route? For example, if you have entered ‘http://loalhost:3000/task’, it will respond with “Cannot GET /task”. Middleware could be added, which could be used for returning messages that are more interactive.
Middlewares intercept incoming Http requested; thus, they could be used for several operations. To do this, open the server.js file, then paste the code.
If a wrong route is entered on the site, the snippet above helps redirect and respond.