Build­ing REST APIs with the LoopBack Frame­work

LoopBack is an open source Node.js frame­work, with which you can quickly cre­ate REST APIs, and con­nect de­vices and browsers to data and ser­vices. LoopBack helps to eas­ily cre­ate client apps with An­droid, iOS and An­gu­larJS SDKs, and comes with add-on compo

OpenSource For You - - Contents - By: Ra­jesh Sola The au­thor is a fac­ulty mem­ber of C-DAC’s Ad­vanced Com­put­ing Train­ing School, and an evan­ge­list in the em­bed­ded sys­tems and IoT do­mains. You can reach him at ra­jesh­sola@gmail.com

LoopBack is a Node.js frame­work that is used to de­sign highly-ex­ten­si­ble, pow­er­ful back-end ser­vices for mo­bile and Web ap­pli­ca­tions. It en­ables dy­namic endto-end REST APIs with lit­tle or zero cod­ing ef­fort through its user-friendly wiz­ard sup­port. It is built on the top of Ex­press. js and adapts most of its func­tion­al­ity like mod­els, rout­ing, mid­dle­ware, etc, but with min­i­mal cod­ing re­quire­ments. It was in­tro­duced by StrongLoop and is cur­rently main­tained jointly by StrongLoop and IBM. It also comes with good in­te­gra­tion sup­port for client-side ap­pli­ca­tion de­vel­op­ment with the avail­able SDKs. This ar­ti­cle cov­ers some LoopBack concepts and takes you through the few steps to build a small server ap­pli­ca­tion for a weather sta­tion.

In­stal­la­tion and build­ing your first ap­pli­ca­tion

The cur­rent pro­duc­tion re­lease is LoopBack v3.0, with long term sup­port (LTS) for v2.x. In­stall the LoopBack CLI tool, which pro­vides var­i­ous wiz­ards for gen­er­at­ing ap­pli­ca­tions, mod­els, data sources, ac­cess con­trol rules, etc, as fol­lows. Choose any LTS ve­ri­ons of Node.js and a com­pat­i­ble npm util­ity for the cur­rent work.

npm in­stall loopback-cli -g

The IBM API Con­nect De­vel­oper Kit is an­other so­lu­tion which uses LoopBack in­ter­nally. In this ar­ti­cle, we’ll fo­cus on the LoopBack CLI tool and v2.x LTS. Let’s fol­low the steps shown be­low to cre­ate a sim­ple app us­ing the ap­pli­ca­tion gen­er­a­tor.

lb app

? What’s the name of your ap­pli­ca­tion? (osfy-demo)

? Which ver­sion of LoopBack would you like to use?

2.x (long term sup­port)

? What kind of ap­pli­ca­tion do you have in mind? api-server

Al­ter­na­tively, you could also choose hello-world or notes as ini­tial tem­plates. Af­ter com­plet­ing this wiz­ard, all the re­quired mod­ules will be in­stalled in the node_­mod­ules sub-di­rec­tory.

Then run the server as fol­lows:

node . (or) npm start

…which will prompt the fol­low­ing URLs to the launch home page and a Swag­ger UI for the REST in­ter­face.

Web server lis­ten­ing at: http://0.0.0.0:3000

Browse your REST API at: http://0.0.0.0:3000/ex­plorer

You may choose any process man­ager like pm2 for bet­ter man­age­ment of the server.

Work­ing with mod­els

Mod­els, which rep­re­sent back-end data sources or ser­vices, are the heart of LoopBack. They come with full-fea­tured REST APIs. Built-in mod­els are cre­ated im­plic­itly as per the ap­pli­ca­tion tem­plate; users add cus­tom mod­els with the help of gen­er­a­tion wiz­ards.

Let’s add a model us­ing a gen­er­a­tor for this app, which rep­re­sents some en­vi­ron­men­tal pa­ram­e­ters like tem­per­a­ture, hu­mid­ity, pres­sure, etc.

lb model

? En­ter the model name: Weather

? Se­lect the data­source to at­tach weather to: db (mem­ory) ? Se­lect model’s base class : Per­sist­edModel

? Expose weather via the REST API? Yes

? Cus­tom plu­ral form (used to build REST URL): Weather ? Com­mon model or server only? com­mon

You can iden­tify the gen­er­ated file for the cre­ated model as weather.json in the com­mon/mod­els sub­di­rec­tory. The de­fault plu­ral form is mostly suit­able for model names, e.g., ‘De­vices’ is ap­pli­ca­ble if the model name is ‘De­vice’. But for the cur­rent model, we’ll use the cus­tom plu­ral form, as ‘Weath­ers’ is not a suit­able plu­ral form. Let’s add a few prop­er­ties to this model, say de­vi­ceid as the string, and tem­per­a­ture, hu­mid­ity, pres­sure as the num­ber with a suit­able choice for Re­quired fields and De­fault values. You can also add more prop­er­ties af­ter com­plet­ing the wiz­ard us­ing the fol­low­ing com­mand or by man­u­ally edit­ing weather.json:

lb prop­erty

Con­nect­ing with data sources

Model in­stances (prop­erty values) are stored un­der the in-mem­ory data­base, by de­fault. You can opt for bet­ter per­sis­tency sup­port with suit­able con­nec­tors for pop­u­lar SQL and NoSQL based data­bases like MySQL, Mon­goDB, etc.

Let’s use the fol­low­ing steps to cre­ate a new data source and at­tach the model to it:

lb data­source

? En­ter the data­source name: mydb

? Se­lect the con­nec­tor for mydb: MySQL

? Con­nec­tion String url to over­ride other set­tings: ? host: lo­cal­host

? port: 3306

? user: root

? pass­word: ****

? data­base: loopback

? In­stall loopback-con­nec­tor-mysql@^2.2 (Y/n)Yes

This will in­stall loopback-con­nec­tor-mysql in node_ mod­ules and gen­er­ate JSON con­tent for the data source in server/data­sources.json. This file can be edited for fur­ther changes once the wiz­ard com­pletes its tasks. To at­tach this data source to our ‘weather’ model, edit server/mod­el­con­fig.json as fol­lows, re­plac­ing db with mydb:

“Weather”: {

“data­Source”: “mydb”, “pub­lic”: true }

LoopBack comes with sup­port for pre­par­ing schema with ap­pli­ca­ble ta­bles or col­lec­tions in cho­sen data­bases; so, let’s add a script in server/boot, say pre­pare-schema.js with the fol­low­ing con­tent: mod­ule.exports = func­tion(app) { app.data­Sources.mydb.autoup­date(‘Weather’, func­tion(err) { if (err) throw err; con­sole.log(‘Schema cre­ated for Weather model: \n’); });

Cre­ate the data­base loopback in MySQL and launch the server. You can ob­serve that any up­da­tion in model in­stances is re­flected in the cho­sen data­base un­der the ta­ble with the same name as the model. You can fol­low sim­i­lar steps for other data­bases like Mon­goDB, with suit­able con­nec­tors.

Ex­plor­ing REST APIs

Each gen­er­ated model comes with full-fea­tured REST APIs with ‘cre­ate, read, up­date and delete’ (CRUD) op­er­a­tional sup­port on model in­stances. You can ex­plore these APIs us­ing the Swag­ger UI avail­able at host­name:3000/ex­plorer. Let’s per­form the fol­low­ing REST op­er­a­tions to add a new in­stance:

POST /api/Weather { “de­vice-id”:”rpi123” “tem­per­a­ture”: 18, “hu­mid­ity”: 72, “pres­sure”: 1060 }

And to re­trieve all model in­stances, use the fol­low­ing com­mand:

GET /api/Weather

You can also add fil­ters to re­trieve spe­cific in­stances in a par­tic­u­lar or­der. Ex­am­ples are given be­low.

To list in­stances with a spe­cific de­vice ID, type: {“where” : {“de­vice-id”: “rpi3”}}

To re­trieve in­stances match­ing cer­tain cri­te­ria, give the fol­low­ing com­mand:

{“where” : {“tem­per­a­ture”: {“gt”:”20”}}}

To list in an as­cend­ing or­der, type:

{“or­der” : “tem­per­a­ture ASC”}

These fil­ters are en­coded in the URL query string as ‘fil­ter=<url­en­coded­cri­te­ria>’ with HTTP re­quests.

You can play around with other REST end­points and verbs ex­posed on the cur­rent model through this UI, and also ob­serve the equiv­a­lent Curl com­mand us­age for mak­ing re­quests us­ing any other client.

Adding a Web tem­plate

You can add some static Web con­tent as the home page. For this, edit the files sec­tion in server/mid­dle­ware.json as fol­lows, to de­fine the static mid­dle­ware: “files”: {

“loopback#static”: { “params”: “$!../client” } },

Then dis­able server/boot/root.js by re­mov­ing or re­nam­ing it with an ex­ten­sion other than .js.

Now place any static pages with HTML, CSS and clientside script­ing con­tent un­der the client sub-di­rec­tory, which will serve as a home page for your ap­pli­ca­tion.

Au­then­ti­ca­tion and au­tho­ri­sa­tion

LoopBack comes with good sup­port for au­then­ti­ca­tion and ac­cess con­trols through its built-in mod­els — User, Ac­cessTo­ken, ACL, RoleMap­ping and Role. To cre­ate data­base schema for these mod­els, add a small pro­ce­dure in a .js file as de­scribed in http://loopback.io/doc/en/lb2/Cre­at­ing-databaseta­bles-for-built-in-mod­els.html and ex­e­cute it once. To cre­ate a new user, do a POST op­er­a­tion on /api/Users with the fol­low­ing pay­load: { “email”: “abc@strongloop.com”, “pass­word”: “hello123”, “emailVer­i­fied”:true }

You may add other prop­er­ties like realm for real name, and user­name in the above pay­load. Now log in with a POST op­er­a­tion on /api/Users/lo­gin us­ing the pay­load with a reg­is­tered email ID and pass­word, which re­turns a re­sponse with ac­cessTo­ken, with prop­erty name id and a ttl value for va­lid­ity. The de­fault va­lid­ity pe­riod for ac­cessTo­ken is two weeks. { “id”:”xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”, “ttl”: 1209600, }

You can use this gen­er­ated to­ken for fur­ther au­then­ti­ca­tion. In the Swag­ger UI, this to­ken can be set in the field which ap­pears at the top right cor­ner, which adds a name-value pair to query string for au­then­ti­ca­tion. For ex­am­ple, to re­trieve the list of in­stances, the fol­low­ing REST op­er­a­tion is used.

GET /api/Weather?ac­cess_­to­ken=xxxxxxxxxxxxxxxxxxxxxxx

You can per­form a POST op­er­a­tion on /Users/lo­gout to in­val­i­date the to­ken ex­plic­itly.

ACL rules spec­ify the ac­cess priv­i­leges on cre­ated mod­els for users. Let’s deny ac­cess to all prop­er­ties of the cur­rent model to all users, ini­tially.

lb acl

? Se­lect the model to ap­ply the ACL en­try to: Weather ? Se­lect the ACL scope: All meth­ods and prop­er­ties ? Se­lect the ac­cess type: All (match all types)

? Se­lect the role All users

? Se­lect the per­mis­sion to ap­ply Ex­plic­itly deny ac­cess

Now, let’s grant ac­cess to any au­then­ti­cated user:

? Se­lect the role : Any au­then­ti­cated user

? Se­lect the per­mis­sion to ap­ply : Ex­plic­itly grant ac­cess

You can ob­serve these gen­er­ated ACL rules un­der the model-spe­cific JSON file in com­mon/mod­els, i.e., weather. json in our ex­am­ple. With these rules, you can ob­serve that only au­then­ti­cated users can per­form CRUD op­er­a­tions via REST on the Weather model.

Fea­ture sum­mary

Here is the sum­mary of some more fea­tures of LoopBack, which do prove that it can be the per­fect choice for a ‘Back­end as a Ser­vice’ (BaaS) for Web ap­pli­ca­tions, and for con­nected smart de­vices in

IoT ap­pli­ca­tions.

Ex­tends REST API us­ing re­mote meth­ods, re­mote hooks and op­er­a­tional hooks.

Model hi­er­ar­chy and re­la­tion­ships for real world ob­ject map­ping.

Data val­i­da­tion mech­a­nism for model in­stances be­fore stor­ing in data source.

Rout­ing and mid­dle­ware sim­i­lar to Ex­press.js. Real-time ‘server sent events’ (SSE) sup­port for live up­dates.

Client-side SDKs for An­droid, iOS, Xa­mar­ian and An­gu­lar.JS apps to in­ter­act with mod­els in an el­e­gant mode, elim­i­nat­ing clunky HTTP in­ter­faces and com­plex data for­mats.

Sends push no­ti­fi­ca­tions us­ing Ap­ple Push No­ti­fi­ca­tion Ser­vice (APNS) for iOS and Google Cloud Mes­sag­ing (GCM) ser­vices for An­droid apps.

Auto gen­er­a­tion of An­gu­lar ser­vices for clientside rep­re­sen­ta­tion of mod­els.

OAuth2.0 and Pass­port based au­then­ti­ca­tion for third party lo­gins.

Com­po­nents for con­tent man­age­ment on pop­u­lar cloud stor­age providers.

Off­line syn­chro­ni­sa­tion sup­port.

Ease of de­ploy­ment on PaaS plat­forms like Bluemix, OpenShift, Heroku, etc.

LoopBack can also be a per­fect choice for ‘Mo­bile Back­end as a Ser­vice’ (MBaas), es­pe­cially with its sup­port for client SDKs, push no­ti­fi­ca­tions, off­line syn­chro­ni­sa­tion and cloud de­ploy­ment. You can find the en­tire code for the ex­am­ple dis­cussed in this ar­ti­cle at github.com/ ra­jesh­sola/iot-ex­am­ples/tree/mas­ter/loop­back­demo, and some more hints on the README page of this di­rec­tory.

Ref­er­ences [1] http://loopback.io/doc/en/lb2/index.html [2] http://loopback.io/doc/en/lb2/LoopBack­core-concepts.html

Fig­ure 1: Swag­ger UI for REST APIs

Fig­ure 2: Ac­cess to­ken in REST Ex­plorer

Newspapers in English

Newspapers from India

© PressReader. All rights reserved.