Building a RESTful API Using LoopBack
Learn how to build a RESTful API project using the open source LoopBack framework, and connect it to a MongoDB database.
Join the DZone community and get the full member experience.
Join For FreeOverview
LoopBack, an easy to learn and understand open-source Node.js framework, allows you to create end-to-end REST APIs with less code compared to Express and other frameworks. It allows you to create your basic routes on adding a model into the application.
Data can be accessed from multiple databases such as MySQL, MongoDB, Oracle, MS SQL, PostgreSQL, and so on. In this blog post, let us discuss building a RESTful API using LoopBack and accessing data from MongoDB.
Installing LoopBack
LoopBack can be installed using either API Connect or StrongLoop. To install using StrongLoop, use the below command:
$ sudo npm install -g strongloop
Creating a Sample Project
In this section, let us discuss creating a sample project.
Creating an Application
To create an application, use the below command:
$ slc loopback
Accept the default selection api-server to create the application.
Connecting to the Database
To connect to the database such as MySQL/MongoDB, use the below command:
$ npm install loopback-connector-mongodb–save
Creating a Model
The models are connected to databases via data sources providing create, retrieve, update, and delete (CRUD) functions.
Other backend services such as REST APIs, SOAP web services, and storage services, and so on are generalized as data sources.
To create a model, use the below command:
$ slc loopback:model
Running Application
To run the application, use the below command:
$ node server.js
$ slc run
Creating a Static HTML Page
To create a static HTML page, perform the following:
- Comment the default root configuration from the following file:
server/boot/root.js
--- disable the code ---
module.exports = function(server) { // Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/', server.loopback.status());
server.use(router);
};
- Add the root configuration from the below file path:
server/middleware.json
...
"files": {
"loopback#static": {
"params": "$!../client"
}
},
...
The above lines define static middleware, making the application serve files in the client directory as static content. The $! characters indicate that the path is relative to the location of middleware.json.
The page looks similar to the one below:
MongoDB Collection
A collection called studentmodel is created in MongoDB as shown in the below diagram:
Creating a Custom API
To create a custom API to access data from MongoDB [Extend API], perform the following:
- Use the below root configuration file:
common/models/studentmodel.js
- Select data from MongoDB based on the API request using the below command:
Studentmodel.getName = function(shopId, cb) {
Studentmodel.findById( shopId, function (err, instance) {
var response = "Name of coffee shop is " + instance.name;
cb(null, response);
console.log(response);
});
}
Studentmodel.remoteMethod (
'getName',
{
http: {path: '/getname', verb: 'get'},
accepts: {arg: 'id', type: 'string', http: { source: 'query' } },
returns: {arg: 'name', type: 'string'}
}
);
The screen looks similar to the one shown below:
Insert data into MongoDB based on the API.
api : /api/studentmodels/addstudent?name=cc&category=fresh
/** To insert data into mongodb from api **/
Studentmodel.addStudent = function(stuname,stucateg, cb) {
var newstu = {"name": stuname, "category": stucateg};
Studentmodel.create( newstu, function (err) {
var response = "Successfully inserted";
cb(null, response);
console.log(response);
});
}
Studentmodel.remoteMethod (
'addStudent',
{
http: {path: '/addstudent', verb: 'get'},
accepts: [{arg: 'name', type: 'string', http: { source: 'query' } },{arg: 'category', type: 'string',
http: { source: 'query' } }],
returns: {arg: 'response', type: 'string'}
}
);
The screen looks similar to the one shown below:
The database table is as follows:
Before Inserting Data Into Database
After Inserting Data Into Database
Destroy model instance with the specified ID.
api: /api/studentmodels/removestudent?id=591edf53a593f55ec705595c
/** Destroy model instance with the specified ID **/
Studentmodel.removeStudent = function(stuid, cb) {
Studentmodel.destroyById( stuid, function (err) {
var response = "Successfully removed";
cb(null, response);
console.log(response);
});
}
Studentmodel.remoteMethod (
'removeStudent',
{
http: {path: '/removestudent', verb: 'get'},
accepts: {arg: 'id', type: 'string', http: { source: 'query' } },
returns: {arg: 'response', type: 'string'}
}
);
The screen looks similar to the one shown below:
The database table is as follows:
Before Deleting Data From Database
After Deleting Data From Database
Update the model instance with the specified ID. Replace attributes for the model instance whose ID is the first input argument, persist it into the data source, and perform validation before replacing.
api: /api/studentmodels/updateStudent?id=591eddaba593f55ec705595b&name=ccccc&categ=manag
/** Update instance of model with the specified ID **/
Studentmodel.updateStudent = function(stuid, stuname,stucateg,, cb) {
var newstu = {"name": stuname, "category": stucateg};
Studentmodel.replaceById( stuid,newstu, function (err) {
var response = "Successfully removed";
cb(null, response);
console.log(response);
});
}
Studentmodel.remoteMethod (
'updateStudent',
{
http: {path: '/updatestudent', verb: 'get'},
accepts: [{arg: 'id', type: 'string', http: { source: 'query' } }, {arg: 'name', type: 'string', http: {
source: 'query' } },{arg: 'category', type: 'string', http: { source: 'query' } }],
returns: {arg: 'response', type: 'string'}
}
);
The screen looks similar to the one shown below:
The database table is as follows:
Before Updating Data Into Database
After Updating Data Into Database
Published at DZone with permission of Rathnadevi Manivannan. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Demystifying SPF Record Limitations
-
Does the OCP Exam Still Make Sense?
-
How Agile Works at Tesla [Video]
-
You’ve Got Mail… and It’s a SPAM!
Comments