Let's refer to the article below by Mytour to learn more about RESTful API in Node.js, and how to create RESTful API in Node.js.
What is RESTful API in Node.js?
1. What is REST?
2. Preparation
3. How to create RESTful API with Node.js
4. Setting up Server
5. Setting up schema
6. Setting up route
7. Setting up Controller
8. Connecting everything together
9. Testing with Postman
10. Adding middleware
1. What is REST?
REST stands for Representational State Transfer, which is a standard web architecture and HTTP protocol. The REST architectural design style describes 6 initial constraints presented by Roy Fielding in his doctoral dissertation and the fundamental definition of RESTful style is:
1. Uniform interface
2. Stateless (Statelessness)
3. Cacheability
4. Client - Server Architecture
5. Layered System
6. On-demand Code (Optional)
RESTful applications use HTTP requests to perform 4 common operations called CRUD, where: C stands for create, which is to make. R stands for read, which means to read. U stands for update, which means to update, and D stands for delete, which means to delete.
RESTful includes methods like base URL, URL, media type, ... . In the next section, Mytour will guide you on how to create a RESTful API using Node.js.
2. Preparation
Before starting the process of creating a RESTful API, here are the tools you need to prepare:
- Node.js
- MongoDB
- Command-line editor (Atom, Sublime, ...)
- Postman
3. Creating RESTful APIs with Node.js
In the next part, Mytour will guide you on creating RESTful APIs. To do this, we'll first create a list of RESTful APIs (i.e., endpoints for creating tasks, fetching or listing all tasks, fetching a specific task, deleting a task, and updating a task).
Assumption
Assuming you've set up your environment (i.e., installed Node.js and MongoDB).
Run the commands npm -v and mongo --version to find out the NPM and MongoDB version information installed on your computer.
After installing Node and MongoDB, follow the steps below to create a RESTful API with Node.js.
Open Terminal, then follow the steps below:
Step 1: Create a new directory named todoListApi by typing the command mkdir todoListApi.
Step 2: Navigate to the root directory of the newly created directory by typing the command cd todoListApi.
Step 3: Next, type the command npm init to create a package.json file.
The Package.json file provides necessary information for npm, allowing it to identify the project and handle project dependencies.
npm init will prompt you to enter some information such as the application name, description, version, author, and keywords.
On the screen, you'll see a window like the one below:
Next, enter Yes and press Enter to complete the package.json creation process. Once completed, the directory structure looks like this:
Step 4: Type the command touch server.js to create a file named server.js.
In this server, we'll write protocols to create the server.
Step 5: Create a directory named api - mkdir api.
Within the api directory, create 3 additional directories named models, routes, and controllers by running the command mkdir api/controllers api/models api/routes.
Step 6: Create todoListController.js in the api/controller directory, todoListRoutes.js in the routes directory, and todoListModel in the models directory by running the command: touch api/controllers/todoListController.js api/models/todoListModel.js api/routes/todoListRoutes.js.
The directory structure will look like this:
4. Setting up the Server
The next step is to install express and nodmon, express is used to create the server while nodmon is used to monitor changes in the application by watching for changed files and automatically restarting the server. Use the following commands:
npm install --save-dev nodemon
npm install express --save
Once express and nodmon are successfully installed, the package.json file will be modified to install the 2 new packages.
1. Open the package.json file and add this task to the scripts:
'start': 'nodemon server.js'
2. Open the server.js file and paste the following code:
var express = require('express'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port);
console.log('Server for the todo list RESTful API has been started on: ' + port);
3. In the Terminal window, run the command npm run start to start the server. You will see the following message on the screen:
todo list RESTful API server started on: 3000
5. Setting up the schema
First step is to install mongoose, using the command npm install mongoose --save .
We'll be using Mongoose to interact with a MongoDB database instance. After installing Mongoose, open the todoListModel.js file in the api/models directory, input the following code into the file, and save it:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TaskSchema = new Schema({
name: {
type: String,
required: 'Please enter the task name'
},
Created_date: {
type: Date,
default: Date.now()
},
status: {
type: [{
type: String,
enum: ['pending', 'in progress', 'completed']
}],
default: ['pending']
}
});
module.exports = mongoose.model('Tasks', TaskSchema);
The provided code adds mongoose to the file, then creates a model describing how the collection should be displayed.
As you can see, the task collection (table) will contain a name as a string and a creation date, with the task status defined as pending - the default value for each task created.
6. Set up routes
Routes refer to how the application handles client requests at a specific endpoint, which is a URL (or path) and a specific HTTP request method (GET, POST, etc.).
Each route has a different handler function, which is executed when the route is matched.
Below are 2 basic routes ('/tasks' and '/tasks/taskId') with different methods.
'/tasks' has two methods ('GET' and 'POST'), while '/tasks/taskId' has GET, PUT, and DELETE.
Next, we will require a controller for each method of the route to be able to invoke the corresponding processing function.
To do this, open the todoListRoutes.js file in the routes folder and input the following code:
'use strict';
module.exports = function(app) {
var todoList = require('../controllers/todoListController');
// Routes for Managing Tasks
app.route('/tasks')
.get(todoList.list_all_tasks)
.post(todoList.create_a_task);
app.route('/tasks/:taskId')
.get(todoList.read_a_task)
.put(todoList.update_a_task)
.delete(todoList.delete_a_task);
};
7. Setting up Controller
Open the todoListController.js file using a command-line text editor on your computer.
In this Controller, we will write 5 different functions, including: list_all_tasks, create_a_task, read_a_task, update_a_task, delete_a_task. Then export each function to use in the routes.
Each function will utilize different mongoose methods, including find, findById, findOneAndUpdate, save, and remove.
'use strict';
var mongoose = require('mongoose'),
Task = mongoose.model('Tasks');
exports.list_all_tasks = function(req, res) {
Task.find({}, function(error, task) {
if (error)
res.send(error);
res.json(task);
});
};
exports.create_a_task = function(req, res) {
var new_task = new Task(req.body);
new_task.save(function(err, task) {
if (err)
res.send(err);
res.json(task);
});
};
exports.read_a_task = function(req, res) {
Task.findById(req.params.taskId, function(err, task) {
if (err)
res.send(err);
res.json(task);
});
};
exports.update_a_task = function(req, res) {
Task.findOneAndUpdate({_id: req.params.taskId}, req.body, {new: true}, function(err, task) {
if an error occurs
send the error
respond with the task in JSON format
});
};
exports.delete_a_task = function(req, res) {
Remove a task where
_id is equal to req.params.taskId
}, function(err, task) {
If there's an error
send the error
Send a JSON response with the message: 'Task successfully deleted'
};
};
8. Connect Everything Together
In the above section, we have the code to set up and run the server in the server.js file. Here, we'll establish connections between controllers, the database, created models, bodyparser, and routes.
Open the server.js file created in the above section and follow the steps below to connect everything together.
Essentially, we'll replace the code in our server.js with the snippet below.
1. Connect to the database by adding the URL to the mongoose connection variable.
2. Load the created model - task.
3. Install bodyParser and use it.
The bodyParser parses the request elements in middleware before the handler, available in the req.body property.
All middleware fills req.body property with bodyParser or an empty object ({}) if there's nothing to parse (or an error is returned).
4. Register the created routes in the server.
const express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
const Task = require('./api/models/todoListModel'), // Loading the created model
bodyParser = require('body-parser');
// Establishing mongoose instance connection URL
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
var routes = require('./api/routes/todoListRoutes'); // Importing the route
routes(app); // Registering the route
app.listen(port);
console.log('todo list RESTful API server started on: ' + port);
5. Start MongoDB server.
Open Terminal and run the command mongod.
This command will start the MongoDB server, then the node server can connect to MongoDB instances. After the MongoDB server is running, restart the node server by running the command rs in the Nodemon Terminal window.
9. Test with Postman
Once everything is connected, try testing each route and its corresponding methods.
Open Postman and enter the command below:
1. Enter http://localhost:3000/tasks into the request URL section and press Enter.
Now the screen will display '[]' because there is nothing in the database yet.
2. At the same address, change the method to POST, click on body, and select 'x-www-form-urlencoded.'
Next, input the name in the key section and the corresponding task in the value section, then click the Send button.
10. Adding Middleware
Suppose if you enter 'http://localhost:3000/task
Essentially, Middleware intercepts http requests, and you can use it to perform various operations, such as authentication, ... .
To achieve this, open the server.js file and paste the following code snippet:
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'})
});
The above snippet will redirect and respond whenever an invalid route is entered on the website.
So, in this article, Mytour has introduced you to what RESTful API is in Node.js. Additionally, readers can refer to other articles on Mytour to further understand what Utility Module and Web Module are in Node.js.