1
votes

I envision loopback's datasources & models as a useful tool for consuming an API, not just for automatically creating a REST API.

Pretend I'm using Spotify's API. I want a command line application that looks up user information on Spotify. I could write loopback models to consume say /v1/albums.

I'm hoping I can create an Album model and use it like Album.find('Thriller');.

What I don't want is to create a REST API. I just want a better language to consume other people's APIs such as Facebook or Instagram.

3
Based on your update, and the statement that you "don't want ... to create a REST API", then I don't think LoopBack is a good choice. It is entirely dedicated to creating REST APIs. - Jordan Kasper

3 Answers

1
votes

A LoopBack model is just a config file and a collection of functions in a model file. All of the endpoints are generated by LoopBack itself, and as such not very helpful by themselves. That said, you can generate a swagger spec for each of your models with the explorer component (installed by default when you use the scaffolding CLI: slc loopback).

Simply start up your LoopBack application, then navigate to:

http://localhost:3000/explorer/resources/MyModels

You could then use the swagger spec in any framework that supports that standard.

1
votes

Loopback has the concept of non-database connectors, including a REST connector. From the docs:

LoopBack supports a number of connectors to backend systems beyond databases.

These types of connectors often implement specific methods depending on the underlying system. For example, the REST connector delegates calls to REST APIs while the Push connector integrates with iOS and Android push notification services.

This is adapted from the documentation for Spotify (I haven't tried this though):

datasources.json

Album": {
  "name": "spotify",
  "connector": "rest",
  "debug": false,
  "options": {
    "headers": {
      "accept": "application/json",
      "content-type": "application/json"
    },
    "strictSSL": false
  },
  "operations": [
    {
      "template": {
        "method": "GET",
        "url": "https://api.spotify.com/v1/albums/",
        "query": {
          "album": "{album}"
        },
        "options": {
          "strictSSL": true,
          "useQuerystring": true
        }
      },
      "functions": {
        "find": ["album"]
      }
    }
  ]
}

You could then call this api from code with:

app.dataSources.Album.find('thriller', processResponse);

-1
votes

One good approach is to use their rest-connector which will allow you to template your request and response calls to the external API, use model validation on the data that comes back and then allow you to persist that new content to your database.