DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

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!

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!
  1. DZone
  2. Data Engineering
  3. Databases
  4. Building a RESTful API Using LoopBack

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.

Rathnadevi Manivannan user avatar by
Rathnadevi Manivannan
·
Jul. 13, 17 · Tutorial
Like (6)
Save
Tweet
Share
15.69K Views

Join the DZone community and get the full member experience.

Join For Free

Overview

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.select






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:select

MongoDB Collection

A collection called studentmodel is created in MongoDB as shown in the below diagram:select

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:select

  • 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:

selectThe database table is as follows:

Before Inserting Data Into Databaseselect

After Inserting Data Into Databaseselect

  • 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:select

The database table is as follows:

Before Deleting Data From Databaseselect

After Deleting Data From Databaseselect

  • 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:select

The database table is as follows:

Before Updating Data Into Database

selectAfter Updating Data Into Databaseselect


API Database REST Web Protocols Data (computing) application

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

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: