Contents


The busy JavaScript developer's guide to LoopBack, Part 1

Hello, World!

Getting started with LoopBack and API Connect

Comments

Content series:

This content is part # of 6 in the series: The busy JavaScript developer's guide to LoopBack, Part 1

Stay tuned for additional content in this series.

This content is part of the series:The busy JavaScript developer's guide to LoopBack, Part 1

Stay tuned for additional content in this series.

JavaScript has been a part of the developer landscape since the mid-'90s, but has only begun to be recognized as a server-side platform in the past few years. Netscape may have been the first to experiment with server-side JavaScript, but it wasn't until Google embedded V8 into a standalone executable (what we now call Node.js) that we saw the potential for running JavaScript code everywhere, not just in a web browser.

Recent interest has sparked an explosion of new frameworks for server-side JavaScript; Meteor, Backbone.js, KeystoneJS, and Sails.js come to mind immediately, and more are there for the research-minded. Each builds on top of certain core primitives and targets more or less the same data storage facilities, but each brings its own flavor to the exercise — a particular way of building applications that will seem most obvious, intuitive, and comfortable to developers already familiar with the style that informs the framework.

As a newcomer to LoopBack, one of your first challenges will be figuring out what to call the technology you're using.

I recently wrapped up my four-part introduction to Sails.js, a JavaScript framework that is conceptually and semantically similar to Rails, the popular web framework for the Ruby language. In this series, I'll introduce LoopBack, a server-side JavaScript framework that emphasizes building HTTP APIs.

LoopBack, StrongLoop, and API Connect

As a newcomer to LoopBack, one of your first challenges will be figuring out what to call the technology you're using. LoopBack was a standalone entity owned by a company called StrongLoop (which was also the name of its paid service offering), until the company was acquired by IBM® in 2015. Since that time, the LoopBack team released a 3.0 version, and starting with this version it's consolidating the terms and names under the IBM banner with IBM API Connect™.

However, much of the framework's documentation is still in a state of flux, and that's to say nothing about the various third-party articles and discussions about LoopBack that float around on the Internet. Thus, the intrepid LoopBack developer most likely will run across all three name variations in the wild, and for that reason they deserve a little bit of explanation.

For the sake of clarity, here's an overview of the three names to know for this project:

  • LoopBack is the open source Node.js framework that provides the core functionality that we'll explore in this series. It's hosted at http://loopback.io, which is the central place for all things LoopBack-related (that is to say, related to the open source framework itself).
  • StrongLoop is the name of the company that has been the principal contributor to LoopBack. Prior to being acquired by IBM in September 2015, StrongLoop released commercialized services and products, including a browser-based GUI design and management tool called StrongLoop Arc. In addition to a graphical interface, Arc featured built-in process monitoring, performance analysis, and other operational support. Although Arc still exists, the clear intent of the current project is to move much of Arc's functionality over to the IBM version of the same product, called API Connect.
    Editorial note: As of April 2017, Arc has been EOL'd and replaced with API Connect. If you are currently a registered user, you can continue to work with Arc.
  • IBM API Connect is the emerging IBM product that picks up where StrongLoop Arc left off, leveraging IBM Bluemix as an API lifecycle management platform and secure, scalable hosting service. API Connect is the name of both the browser-based GUI tool and the paid service, as well as a local command-line utility (apic), but typically the distinction between each of these will be obvious from the context of its usage.

Over the past year, the LoopBack team has been moving documentation from the StrongLoop website to LoopBack's web properties, but as of this writing, the transition is not complete, and some docs still live at StrongLoop. (The LoopBack team has links to the list of planned tasks on its home page, and the documentation itself is hosted in the LoopBack GitHub documentation repo. For those developers for whom the transition is not happening quickly enough — feel free to submit a few pull requests!)

Over time, IBM and StrongLoop will continue to consolidate their holdings, stratifying the product line into two products: the open source LoopBack framework and the commercial platform of API Connect. In the meantime, with just a bit of juggling between the documentation and the reference implementation, we can still use this feature-rich framework.

With that elephant in the room now discussed and dismissed, let's get started, shall we?

Install and set up LoopBack

Like most JavaScript-based frameworks, LoopBack is accessible via npm and makes use of a globally installed command-line tool. The first step to getting started with LoopBack, thus, is to open a command-line terminal with Node.js on the PATH, and use npm to install it: npm install -g apiconnect.

Once LoopBack is done downloading all the necessary bits and installing them to the global Node.js repository on your local machine, you'll see that it has placed a new command-line tool (apic) on your PATH. Use the following command to ensure that the tool is installed and available for your use: apic--help. After entering this command you should get back a fairly detailed list of options.

Currently, the command-line tool is your primary interface for working with LoopBack, so you'll need to use it to create a new application. Since the first application that anyone ever creates in a new environment is the ubiquitous homage to the universe — Hello, World! — we'll start there.

Hello, and good day!

Start by entering the command to create a new application: apic loopback. You'll get back a series of interactive questions. (If you've ever used the JavaScript scaffolding tool Yeoman, you'll recognize the friendly Englishman and his engaging style.) LoopBack will first ask the name of the application you want to scaffold and the directory where you'll do the scaffolding. Since you're just starting out with LoopBack, let's call this app hello and have it generate into a hello subdirectory.

Next, LoopBack asks what kind of application you want to generate. You may choose from these options:

  • empty-server: For those who don't like the LoopBack defaults
  • hello-world: The ubiquitous starter app — we'll use this one for now
  • notes: A full-fledged sample server

After you select hello-world, LoopBack generates some code and runs npm install, which will pull down all the dependencies you need to run the project.

Next, LoopBack will prompt you to run the project. Before doing that, let's take a quick look at the set of files that it generated. (Note that I've omitted a few configuration files, such as .gitignore):

  Created common
  Created common/models
  Created common/models/message.js
  Created common/models/message.json
  Created package.json
  Created server
  Created server/boot
  Created server/boot/root.js
  Created server/config.json
  Created server/datasources.json
  Created server/middleware.json
  Created server/middleware.production.json
  Created server/model-config.json
  Created server/server.js

Notice that the server and common directories are chock full of files, yet there is no client subdirectory. This is because LoopBack isn't a "full-stack" solution. Instead, it's a server-only solution, designed to create API endpoints accessible over HTTP. A front-end developer can then use those endpoints to create rich web or mobile clients for a variety of application requirements. Thus, everything in LoopBack runs on the server, with almost no client presence.

LoopBack does make client-side SDKs available, but there's a strong emphasis on server-side artifacts, and all code written in LoopBack assumes execution on the server. This is in direct contrast to a full-stack environment such as Meteor, which looks to minimize friction between client-side development and the server.

Now let's see LoopBack in action.

Your first LoopBack API

You can use apic to kick off the server process, or you can let npm launch it. Go to the hello directory (the parent to the client, common, and server subdirectories), where the package.json file resides. There, you'll issue either the apic start or npm start command; either one will fire up the server to start listening for incoming requests.

Pretty quickly, you'll see console messages telling you that your first LoopBack application is running; check the console, however, to find out which port the application is bound to, since it will differ depending on how you launched the code.

Listing 1. LoopBack 'Hello'
    $ npm start

    > hello@1.0.0 start /Users/tedneward/Projects/hello
    > node .

    Web server listening at: http://0.0.0.0:3000
    Browse your REST API at http://0.0.0.0:3000/explorer

Given the above console message, to complete the exercise you'd need only to open a web browser and point it to http://localhost:3000. You'll get a ... something.

The root URL

As welcome messages go, the message LoopBack displays isn't particularly hello-ish. In fact, what you see is not the actual "hello" message, but the app's uptime. This root URL uptime reporting is a standard feature of any LoopBack-generated application, providing an endpoint to ping against in order to determine whether the server is reachable. You can also use this endpoint as a simple diagnostic tool to find out whether the server has gone down since the last time anyone thought to look.

However, if you want to see the actual greeting, you need to hit a different URL. To know what URL to hit, you need to be able to discover it. One way would be to navigate through the source code, find the routes configured for the application, and piece it together based on any parameters that may or may not be passed. Or, you could browse the application in a more graphical fashion.

LoopBack with API Connect

Assuming you've registered and logged in to Bluemix, you have the credentials you need to access API Connect. Depending on how you started the server, shut it down now with npm stop or apic stop. Next, run apic edit. After a few seconds, you'll get a message that the Express server is listening on localhost, and a browser window pointing to a specified URL (mine is http://localhost:9000, as of this writing) will open.

Once you've logged in, the API Connect dashboard will show the hello project, currently tagged as version 1.0.0. Across the bottom, the status of the server is displayed, currently reading "Stopped." Beside the status will be a triangle, symbolizing "Play." Click the triangle to restart the server.

Clicking on the hello link in the central area of the dashboard will take you to the APIs section of the dashboard. The various API endpoints that are exposed by your application (or product) are displayed here. This is the Design view of the API, offering a user-friendly view of a Swagger API declaration for your app/product. To see the actual Swagger document, click Source in the toolbar. Use the options along the left to navigate to different parts of the Swagger documentation. (See Figure 1.)

Figure 1. Swagger document for the hello application
Screenshot of the Swagger document for the hello application
Screenshot of the Swagger document for the hello application

Swagger documentation gives you many options, most of them beyond the scope of what we want to do here. So for now, cruise down the left-hand side of options and click on Paths: This is the portion of the Swagger specification that describes the endpoints that are exposed from the service. As you can see, one such path is defined, described as /Messages/greet. It isn't quite the full path, however, because the Swagger specification also sets a Base Path (viewable at the top of the options list) of /api, which means the entire URL is /api/Messages/greet.

Before we do anything else, note that LoopBack, like many REST-oriented frameworks, is designed around the concept of resources, which LoopBack describes as models. We'll go into this more in Part 2, but let's take a minute to view the application's model architecture. In the API Connect GUI, click All APIs. This will take you back to the main dashboard, where you should select Models. For this simple hello application, API Connect has defined one model type, called Message. Currently this model is empty. We don't need to do anything with it yet, so that's okay.

Exploring the GUI

Now that we know the application URL, we could immediately turn to cURL or Postman or some other simple HTTP client tool to hit the endpoint with an HTTP request and see what comes back. But even then, you might forget about a parameter. And if the API wants to sit behind some level of security (via user authentication), then you're going to need to remember to put those credentials in place every time you run it. Fortunately, API Connect provides us an easier mechanism, at least for ad hoc scenarios.

In the upper-right corner of the GUI there is a button labeled Explore. Click it and you'll be taken to the interactive part of the API Connect dashboard. On the left, you'll see a long list of calls. On the right, below the code example section, is a set of edit fields for accepting the parameters to the API. After selecting GET /Message/greet you'll find the msg parameter here, where you can add your greeting: Hello. Below that sits the Call operation button, which will send out an HTTP request and display the result. (See Figure 2.)

Figure 2. Calls and parameters in the API Connect GUI
Screenshot of the API Connect GUI showing calls and parameters
Screenshot of the API Connect GUI showing calls and parameters

Of course, you don't need to go through the GUI to hit the actual endpoint. To run the curl request, you could copy and paste the curl command line into the CLI. Or, if you prefer, you could copy and paste the URL request into the address bar of your browser, in which case you would see the following:

    {"greeting":"Sender says Hello to receiver"}

There; that's much friendlier.

Conclusion

For something as small as a Hello, World application, LoopBack offers a hefty set of features and tools to work with. It's just up to you how you greet each feature. You might prefer to work out of a GUI-based environment such as API Connect. Or you could be a command-line junkie like me, who simply cannot seem to embrace the mouse- or swipe-driven world. Fortunately, there's really no difference on the functionality side: The developers at StrongLoop (and now IBM) have done an excellent job of making sure that we'll find ourselves at home with LoopBack regardless of whether we approach it via the command line or the GUI.

As we end this first foray into LoopBack, you might note that you've yet to write a single line of JavaScript code — and that's only the beginning of the surprises that LoopBack has in store. In the next installment you'll learn how to define models (resources, in REST parlance) and do the usual CRUD operations on any of LoopBack's supported data sources. As a spoiler alert, you'll also find that LoopBack makes it remarkably easy to define models against an existing data source. Take, for example, your 20-year-old relational database schema.


Downloadable resources


Related topics


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, Open source
ArticleID=1043601
ArticleTitle=The busy JavaScript developer's guide to LoopBack, Part 1: Hello, World!
publish-date=03072017