Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Loopback to Build APIs for APIs

DZone's Guide to

Using Loopback to Build APIs for APIs

Building APIs for APIs sounds like infinite recursion, but I’m talking about one cool aspect of LoopBack: the ability to define a server API that maps to another server.

· Integration Zone
Free Resource

Learn how API management supports better integration in Achieving Enterprise Agility with Microservices and API Management, brought to you in partnership with 3scale

“Building APIs for APIs” sounds a bit like infinite recursion, but actually I’m talking about one of the cooler aspects of LoopBack: the ability to define a server API that maps to another server. Essentially your API acts as a proxy for another API. There are a lot of reasons you may want to do this, including:

  • Supplementing the set of APIs you already provide. Perhaps you’re a sports company that can provide APIs for every sport but golf. If you can find a third-party provider for golf data, then you can then add it to your own library and offer a more complete solution to your users.
  • Modifying API results to fit your needs. Maybe you want to use an API that is a bit inflexible in the data it returns. By creating your own proxy, you can modify the result sets to return only what you need.
  • To improve performance, you can add your own caching layer.
  • Perhaps you want to use an API in your mobile app but don’t want to embed sensitive information, like an API key, in your source code. You can use your own server, and this LoopBack feature, to keep the key hidden in your Node.js code.

The feature we’re discussing is provided by the LoopBack “REST Connector.” When you first begin learning LoopBack, you use a connector that stores data in memory. This is great for testing and quick prototyping. You then switch to a persisted connector, like the MongoDB one perhaps, but in general, you’re still doing the same thing. Your models have basic CRUD with the connector in the back to handle persistence.

The REST connector is different. Instead of handling persistence, it handles the connection to the remote API. Let’s take a look at a basic example of the connector in action.

Begin with an existing LoopBack application (or create a new one!), and then install the REST connector:

npm install --save loopback-connector-rest

As a reminder, a standard LoopBack app includes only the in-memory connector, which makes sense if you think about it. There’s no need to include code for Oracle if you are using MySQL.

Next, create a new data source:

slc loopback:datasource

For the name, let’s call it swapi. Our demo is going to make use of the excellent Star Wars API which provides information about everything related to the best thing ever (after cats.)

When prompted to select the connector, scroll down to the REST connector:

sbblog

Next, it will prompt you for the base URL for the API. Here is where things can get tricky. The Star Wars API supports a number of different end points for movies, ships, characters, and more. You’ll want to specify one particular end point. Why?

Unlike the persistence-based data sources, the REST connector is meant to work with one model, not many. In other words, I may set up one MongoDB database for my application and one data source for it in my LoopBack application. I’ll then add many different models all using that one Mongo-based connector.

For the REST connector, we need to point to one API and match it up with one particular model. For this demo, then, we’ll focus on spaceship data because spaceships are awesome.

According to the Star Wars API documentation, we can get a list of spaceships using this URL: http://swapi.co/api/spaceships. So, let’s use that for the connector URL value. For the rest of the prompts, just accept the defaults.

swblog2

At this point, your datasources.json file should look something like this:

{
  "db": {
    "name": "db",
    "connector": "memory"
  },
  "swapi": {
    "name": "swapi",
    "baseURL": "http://swapi.co/api/starships",
    "crud": false,
    "connector": "rest"
  }
}

To work with the remote API, we have to define a set of operations that will be exposed to our local model. You can define as many operations as you need, but most likely you will only need one. An operation consists of a template and a set of functions. The template is a meta description for the remote URL. It allows for tokens so that it can be dynamically updated based on how you call the API. The functions aspect is where you define your own names for accessing the remote API. This all sounds a bit overwhelming, but let’s look at a complete example.

{
  "db": {
    "name": "db",
    "connector": "memory"
  },
  "swapi": {
    "name": "swapi",
    "baseURL": "http://swapi.co/api/starships",
    "crud": false,
    "connector": "rest",
    "operations": [
      {
        "functions": {
          "getships": []
        },
        "template": {
          "method": "GET",
          "url": "http://swapi.co/api/starships/",
          "headers": {
            "accepts": "application/json",
            "content-type": "application/json"
          },
          "responsePath": "$.results.*"
        }
      }
    ]
  }
}

The template aspect defines a lot of different parts of how we’ll call the API. It supports a method and headers, which should look familiar to folks. It obviously needs a URL, and finally, we can define a responsePath to ‘parse’ the result.

responsePath

 is using JSONPath as a way to fetch a portion of a JSON response. In functions, we’ve defined a name for how we want to “address” the URL in the template. The empty array is where we define arguments to pass to the API. For now, we’re not going to pass any arguments at all, so it is empty. There’s a lot we’re leaving o

Unleash the power of your APIs with future-proof API management - Create your account and start your free trial today, brought to you in partnership with 3scale.

Topics:
loopback ,apis ,integration ,rest

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}