Easy way to Build Node JS RESTful APIs
What is REST?
REST stands for Representational State Transfer(sometimes spelled "ReST".) It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used. REST is an architecture style for designing networked applications.There are six constraints of REST:
- Uniform Interface
- Stateless
- Cacheable
- Client-Server
- Layered System
- Code on Demand
In this tutorial, we will learn how to create a simple RESTful APIs using NodeJS + Expressjs + MongoDB
Tools needed:
Get started
Download and Install Node.js & MongoDB
Kindley run following commands to check NPM and MongoDB installed on your machine:npm -v mongo --versionCreate a Folder name restApiExample
mkdir restApiExampleNavigate to the root of your newly created folder
cd restApiExampleNow, init node project and Create a package.json file
npm init
Eventually, you will end up with something like this -
Create a file called server.js
In this file, we will be writing protocols to create our server.
touch server.js
Create a folder called API
Inside this folder name "API" we will have everything to create server i.e API Controller, Models, Routes, etc.$ mkdir apiNow, create 3 mode folders named controllers, models, routes
$ mkdir api/controllers api/models api/routes
Create usersController.js in the api/controllers folder, usersRoutes.js in the api/routes folder and userModel.js in the api/models folder -
$ touch api/controllers/usersController.js api/routes/usersRoutes.js api/models/userModel.jsYour folder structure should look like this now:
Server setup
Let's install express and nodemon, express will be used to create server while nodemon will help to keep track of changes to the application by watching changed files and automatically restart the server.npm install --save-dev nodemon
npm install --save express
Now, Open the server.js file and type/copy the following code into it
var express = require('express'),On your terminal, run
app = express(),
port = process.env.PORT || 3000;
app.listen(port);
console.log('RESTful API server started on: ' + port);
npm run startoutput(in your terminal):
RESTful API server started on: 3030
Setting up the Schema
Let's install mongoose first -npm install --save mongoose
Why Mongoose?
Mongoose is a node package that is used to interact with MongoDB instance.After installation, open the userModel.js file and type/copy the following code into the file and save. Let's define the schema.
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: {
type: String,
required: 'Kindly enter the name'
},
created_date: {
type: Date,
default: Date.now
},
type: {
type: [{
type: String,
enum: ['admin', 'student', 'teacher']
}],
default: ['student']
}
});
module.exports = mongoose.model('Users', UserSchema);
Setting up the Routes
Routing refers to determining how an application will respond to a client request for a specific endpoint, which is the HTTP request method(GET, PUT, POST, DELETE, etc...)Each route is assigned to the different route handler function, which is executed when the route is matched.
We require the controllers to handle function on each of the routes we have defined.
Define Routes-
'use strict';
module.exports = function(app) {
var UsersController = require('../controllers/usersController.js');
// todoList Routes
app.route('/users')
.get(UsersController.listOfUsers)
.post(Users.addUser);
app.route('/users/:userId')
.get(UsersController.getOneUser)
.put(UsersController.updateUser)
.delete(UsersController.deleteUser);
};
Setting up the controller
Define all the functions in usersController.js which are assigned to each of the usersRoutes.'use strict';
var mongoose = require('mongoose'),
Users = require('../models/userModel');
exports.allUsers = function(req, res) {
Users.find({}, function(err, task) {
if (err)
res.send(err);
res.json(task);
});
};
exports.addUser = function(req, res) {
var newUser = new Users(req.body);
newUser.save(function(err, user) {
if (err)
res.send(err);
res.json(user);
});
};
exports.getOneUser = function(req, res) {
Users.findById(req.params.userId, function(err, task) {
if (err)
res.send(err);
res.json(task);
});
};
exports.updateUser = function(req, res) {
Users.findOneAndUpdate({_id: req.params.taskId}, req.body, {new: true}, function(err, user) {
if (err)
res.send(err);
res.json(user);
});
};
exports.deleteUser = function(req, res) {
Users.remove({
_id: req.params.userId
}, function(err, user) {
if (err)
res.send(err);
res.json({ message: 'Task successfully deleted' });
});
};
Almost Done,
Open server.js file- connect with database i.e. MongoDB by adding a URL to the mongoose instance connection
- install bodyParser to parse the API request data
var express = require('express'),
app = express(),
port = process.env.PORT || 3030,
mongoose = require('mongoose'),
bodyParser = require('body-parser')
userRoutes = require('./api/routes/usersRoutes');
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
userRoutes(app);
app.get('/',(req,res)=>{
res.send('RESTful API server started on: ' + port)
})
app.listen(port);
The final thing to do
Open your terminal and start MongoDB servermongod --dbpath <my-db-path>Once the MongoDB server is running, restart node server.
That's all Folks CHEERS!!!.
Originally Published on https://goo.gl/kvYyKE
Github link
No comments:
Post a Comment