Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

loopback-connector-rest

loopbackio68kMIT5.0.5

Loopback REST Connector

LoopBack, REST, DataSource, Connector

readme

loopback-connector-rest

Overview

The LoopBack REST connector enables applications to interact with other (third party) REST APIs using a template-driven approach. It supports two different styles of API invocations:

Installation

In your application root directory, enter:

$ npm install loopback-connector-rest --save

This will install the module from npm and add it as a dependency to the application's package.json file.

Creating a REST data source

Use the data source generator to add a REST data source to your application.

For LoopBack 2.x:

$ apic create --type datasource

For LoopBack 2.x or 3.0:

$ lb datasource

When prompted, scroll down in the list of connectors and choose REST services (supported by StrongLoop). This adds an entry to datasources.json, for example:

...
  "myRESTdatasource": {
    "name": "myRESTdatasource",
    "connector": "rest"
  }
...

LoopBack 4 Usage

  1. Create a LoopBack 4 DataSource with REST connector using the lb4 datasource command.

  2. Create a service that maps to the operations using the lb4 service command.

  3. Create a controller that calls the service created in the above step using lb4 controller command.

For details, refer to the Calling REST APIs documentation page.

Configuring a REST data source

Configure the REST connector by editing datasources.json manually (for example using the Google Maps API):

/server/datasources.json

...
"geoRest": {
  "connector": "rest",
  "debug": "false",
  "operations": [{
    "template": {
      "method": "GET",
      "url": "http://maps.googleapis.com/maps/api/geocode/{format=json}",
      "headers": {
        "accepts": "application/json",
        "content-type": "application/json"
      },
      "query": {
        "address": "{street},{city},{zipcode}",
        "sensor": "{sensor=false}"
      },
      "responsePath": "$.results[0].geometry.location"
    },
    "functions": {
      "geocode": ["street", "city", "zipcode"]
    }
  }]
}
...

The operations property is an array of objects, each of which can have these properties:

The example above creates a function geocode(street, city, zipcode) whose first argument is street, second is city, and third is zipcode. LoopBack application code can call the function anywhere; for example, in a boot script, via middleware, or within a model's JavaScript file if attached to the REST datasource.

Configure options for request

The REST connector uses the request module as the HTTP client. You can configure the same options as for the request() function. See request(options, callback).

You can configure options options property at two levels:

  • Data source level (common to all operations)
  • Operation level (specific to the declaring operation)

The following example sets Accept and Content-Type to "application/json" for all requests. It also sets strictSSL to false so the connector allows self-signed SSL certificates.

/server/datasources.json

{
  "connector": "rest",
  "debug": false,
  "options": {
    "headers": {
      "accept": "application/json",
      "content-type": "application/json"
    },
    "strictSSL": false
  },
  "operations": [
    {
      "template": {
        "method": "GET",
        "url": "http://maps.googleapis.com/maps/api/geocode/{format=json}",
        "query": {
          "address": "{street},{city},{zipcode}",
          "sensor": "{sensor=false}"
        },
        "options": {
          "strictSSL": true,
          "useQuerystring": true
        },
        "responsePath": "$.results[0].geometry.location"
      },
      "functions": {
        "geocode": ["street", "city", "zipcode"]
      }
    }
  ]
}

Resource operations

If the REST API supports create, read, update, and delete (CRUD) operations for resources, you can simply bind the model to a REST endpoint that follows REST conventions.

For example, the following methods would be mixed into your model class:

  • create: POST /users
  • findById: GET /users/:id
  • delete: DELETE /users/:id
  • update: PUT /users/:id
  • find: GET /users?limit=5&username=ray&order=email

For example:

/server/boot/script.js

module.exports = function (app) {
  var ds = app.loopback.createDataSource({
    connector: require("loopback-connector-rest"),
    debug: false,
    baseURL: "http://localhost:3000",
  });

  var User = ds.createModel("user", {
    name: String,
    bio: String,
    approved: Boolean,
    joinedAt: Date,
    age: Number,
  });

  User.create(
    new User({
      name: "Mary",
    }),
    function (err, user) {
      console.log(user);
    }
  );

  User.find(function (err, user) {
    console.log(user);
  });

  User.findById(1, function (err, user) {
    console.log(err, user);
  });

  User.update(
    new User({
      id: 1,
      name: "Raymond",
    }),
    function (err, user) {
      console.log(err, user);
    }
  );
};

Setting the resource URL

You can set the remote URL when using create, read, update, or delete functionality by setting the resourceName property on a model definition. This allows for a local model name that is different from the remote resource name.

For example:

var config = {
  name: "ServiceTransaction",
  base: "PersistedModel",
  resourceName: "transactions",
};

var ServiceTransaction = ds.createModel("ServiceTransaction", {}, config);

Now there will be a resource model named ServiceTransaction, but whose URLs call out to baseUrl - '/transactions'

Without setting resourceName the calls would have been made to baseUrl - '/ServiceTransaction'.

Defining a custom method using a template

The template object specifies the REST API invocation as a JSON template, with the following properties:

Property Description Type
method HTTP method String (one of "GET", "POST", "PUT", and so on).
url The URL of the request String; template values allowed.
headers HTTP headers Object
query Query strings Object; template values allowed.
responsePath Optional JSONPath applied to the HTTP body. See https://github.com/s3u/JSONPath for syntax of JSON paths. String
fullResponse Optional flag to return full response, rather than just body. Boolean

The template variable syntax is:

{name=defaultValue:type}

To specify that the variable value is required, add the prefix ! or ^.

For example:

template: {
    "method": "GET",
    "url": "http://maps.googleapis.com/maps/api/geocode/{format=json}",
    "headers": {
      "accepts": "application/json",
      "content-type": "application/json"
    },
    "query": {
      "address": "{street},{city},{zipcode}",
      "sensor": "{sensor=false}"
    },
    "responsePath": "$.results[0].geometry.location"
  }

The following table provides several examples:

Variable definition Description
'{x=100:number}' Define a variable x of number type and default value 100.
'{x:number}' Define a variable x of number type
'{x}' Define a variable x
'{x=100}ABC{y}123'

Define two variables x and y. The default value of x is 100. The resolved value will be a concatenation of x, 'ABC', y, and '123'. For example, x=50, y=YYY will produce '50ABCYYY123'

'{!x}' Define a required variable x
'{x=100}ABC{^y}123' Define two variables, x and y. The default value of x is 100, and y is required.

To use custom methods, configure the REST connector with the operations property, which is an array of objects, each of which can have these properties:

  • template defines the API structure.
  • functions defines JavaScript methods that accept the specified list of parameter names.
var loopback = require("loopback");

var ds = loopback.createDataSource({
  connector: require("loopback-connector-rest"),
  debug: false,
  operations: [
    {
      template: {
        method: "GET",
        url: "http://maps.googleapis.com/maps/api/geocode/{format=json}",
        headers: {
          accepts: "application/json",
          "content-type": "application/json",
        },
        query: {
          address: "{street},{city},{zipcode}",
          sensor: "{sensor=false}",
        },
        responsePath: "$.results[0].geometry.location",
      },
      functions: {
        geocode: ["street", "city", "zipcode"],
      },
    },
  ],
});

Now you can invoke the geocode API in Node.js as follows:

Model.geocode("107 S B St", "San Mateo", "94401", processResponse);

By default, the REST connector also provides an 'invoke' method to call the REST API with an object of parameters, for example:

Model.invoke(
  { street: "107 S B St", city: "San Mateo", zipcode: "94401" },
  processResponse
);

Parameter/variable mapping to HTTP (since 2.0.0)

NOTE: This feature is available with loopback-connector-rest version 2.0.0 and later.

By default, variables in the template are mapped to HTTP sources based on their root property.

Root property HTTP source
url path
query query
body body
headers header

You can further customize the source in the parameter array of the function mapping, for example:

{
  "template": {
    "method": "POST",
    "url": "http://localhost:3000/{p}",
    "headers": {
      "accept": "application/{format}"
    },
    "query": {
      "x": "{x}",
      "y": 2
    },
    "body": {
      "a": "{a:number}",
      "b": "{b=true}"
    }
  },
  "functions": {
    "myOp": [
      "p",
      "x",
      "a",
      {
        "name": "b",
        "source": "header"
      }
    ]
  }
}

For the template above, the variables will be mapped as follows:

  • p - path
  • x - query
  • a - body
  • b - header

Please note that path variables are appended to the path, for example, /myOp/:p.

changelog

2025-04-14, Version 5.0.5

  • chore(deps): update dependency loopback-datasource-juggler to v5.1.7 (renovate[bot])

  • chore(deps): lock file maintenance (#209) (renovate[bot])

  • chore(deps): update dependency body-parser to v2 (renovate[bot])

  • chore(deps): update dependency multer to v1.4.5-lts.2 (renovate[bot])

2025-03-18, Version 5.0.4

  • chore(deps): update dependency loopback-datasource-juggler to v5.1.6 (renovate[bot])

  • chore(deps): update dependency @commitlint/config-conventional to v19.8.0 (renovate[bot])

  • chore(deps): update dependency loopback-datasource-juggler to v5 (renovate[bot])

  • chore(deps): lock file maintenance (#203) (renovate[bot])

  • fix(deps): update dependency postman-request to v2.88.1-postman.42 (renovate[bot])

  • fix(deps): update dependency jsonpath-plus to v10.3.0 [security] (renovate[bot])

  • chore(deps): update dependency mocha to v11 (renovate[bot])

  • chore(deps): update dependency @commitlint/config-conventional to v19 (renovate[bot])

  • chore(deps): update actions/setup-node action to v4 (renovate[bot])

  • chore(deps): update actions/checkout action to v4 (renovate[bot])

  • fix(deps): update dependency mime to v2.6.0 (renovate[bot])

  • fix(deps): update dependency qs to v6.14.0 (renovate[bot])

2025-02-16, Version 5.0.3

  • chore(deps): update dependency mocha to v10.8.2 (renovate[bot])

  • chore(deps): update dependency eslint-plugin-mocha to v10.5.0 (renovate[bot])

  • fix(deps): update dependency traverse to v0.6.11 (renovate[bot])

  • chore(deps): update dependency @commitlint/config-conventional to v17.8.1 (renovate[bot])

  • fix(deps): update dependency postman-request to v2.88.1-postman.40 (renovate[bot])

  • chore(deps): update dependency eslint to v8.57.1 (renovate[bot])

  • chore(deps): update dependency express to v4.21.2 (renovate[bot])

  • fix(deps): update dependency jsonpath-plus to v10.2.0 [security] (renovate[bot])

  • chore: update renovate bot (dhmlau)

2024-10-17, Version 5.0.2

  • fix: audit issue (siimsams)

2024-03-07, Version 5.0.1

  • feat: replace request with postman-request fork as a drop-in replacement (Samarpan Bhattacharya)

  • fix: fix renovate configs (dhmlau)

  • chore: add renovate.json (renovate[bot])

2023-11-20, Version 5.0.0

  • chore: drop support for nodejs16 and lower BREAKING CHANGE: drop support for nodejs16 and lower (Samarpan Bhattacharya)

2023-03-09, Version 4.0.3

  • chore: update package-lock (dhmlau)

2022-11-14, Version 4.0.2

  • chore: update dependencies (dhmlau)

  • docs: add loopback 4 usage (Shubham Prajapat)

  • docs: add SECURITY.md (Diana Lau)

  • docs: update coc (Diana Lau)

  • docs: add code of conduct (Diana Lau)

  • chore: move repo to loopbackio org (Diana Lau)

  • ci: convert from travis to github actions (Agnes Lin)

2020-11-10, Version 4.0.1

  • feat: force mime define to avoid conflicts (Raymond Feng)

2020-11-05, Version 4.0.0

  • Fix template handling for values with {} (Raymond Feng)

  • update dependencies and fix eslint issues (Raymond Feng)

  • Drop Node 8.x support (Raymond Feng)

  • chore: switch to DCO (Diana Lau)

  • chore: add Node.js 14 to CI (Diana Lau)

2020-06-22, Version 3.7.0

  • fix docs (Tom Riley)

  • Add tests for fullResponse flag (Tom Riley)

  • feat: Implement a flag to return the full response (Tom Riley)

  • chore: update strong-globalize version (Diana Lau)

  • chore: update copyrights year (Diana Lau)

  • chore: improve issue and PR templates (Nora)

2019-10-10, Version 3.6.0

  • update jsonpath-plus dependency to 1.x (Raymond Feng)

  • Updated to correct index on template build (Jee Mok)

2019-09-19, Version 3.5.0

  • add node 12 to CI (Nora)

  • drop support for node 6 (Nora)

2019-07-09, Version 3.4.2

  • fix: update lodash (jannyHou)

  • chore: update copyrights years (Agnes Lin)

  • test: use a local stub of Google Map API (Miroslav Bajtoš)

2018-10-29, Version 3.4.1

  • Fix json path (Raymond Feng)

2018-10-29, Version 3.4.0

  • Update deps (Raymond Feng)

  • Changed testcase description (Ivan Dovgan)

  • Fix lint issue and add test case (xiaoyu zhou)

  • Add support for default values in function defs (Ivan Dovgan)

2018-09-12, Version 3.3.0

  • fix adding attachments to form data (Brian Kwon)

2018-07-20, Version 3.2.0

  • chore: Drop Node.js 4 in CI (Diana Lau)

  • [WebFM] cs/pl/ru translation (candytangnb)

  • Update dependencies to latest (Miroslav Bajtoš)

  • Update eslint + config to latest (Miroslav Bajtoš)

2018-03-30, Version 3.1.1

  • allow tests to detect google map api rate limiting (Raymond Feng)

  • issue 118 object object return in error stack (Elankeeran Vaithiyanathan)

  • Update LICENSE (Diana Lau)

  • chore: update license (Diana Lau)

2017-10-19, Version 3.1.0

  • Fix the template to allow stringified json (Raymond Feng)

  • Add stalebot configuration (Kevin Delisle)

2017-08-21, Version 3.0.0

  • create pr template (Sakib Hasan)

  • create issue template (Sakib Hasan)

  • Update translated strings Q3 2017 (Allen Boone)

  • Add CODEOWNERS file (Diana Lau)

  • update translation file (Diana Lau)

  • add .travis.yml (Diana Lau)

  • Fix api docs (ssh24)

  • Update lb2 to lb3 links (#91) (ivy ho)

  • Update Readme with lb from slc (#90) (ivy ho)

  • Update README.md (#88) (Rand McKinney)

  • Update ko translation file (Candy)

  • Update paid support URL (Siddhi Pai)

  • Start 3.x + drop support for Node v0.10/v0.12 (siddhipai)

  • Drop support for Node v0.10 and v0.12 (Siddhi Pai)

  • Start the development of the next major version (Siddhi Pai)

  • Update README.md (#78) (Rand McKinney)

  • Update README with correct doc links, etc (Amir Jafarian)

2016-10-14, Version 2.1.0

  • Update tests to be port independent (gunjpan)

  • Update translation files - round#2 (Candy)

  • Add translated files (gunjpan)

  • Update deps to loopback 3.0.0 RC (Miroslav Bajtoš)

  • Update juggler in package.json (Amir Jafarian)

  • Globalize using strong-globalize (gunjpan)

  • Update URLs in CONTRIBUTING.md (#65) (Ryan Graham)

  • Add Eslint infrastructure (Amir-61)

  • Fix linting errors (Amir Jafarian)

  • Auto-update by eslint --fix (Amir Jafarian)

  • Add eslint infrastructure (Amir Jafarian)

  • relicense as MIT only (Ryan Graham)

  • insert IBM copyrights (Ryan Graham)

  • Add a test for header var (Raymond Feng)

2016-03-18, Version 2.0.0

  • Derive the http source from the template (Raymond Feng)

  • Allow functions to specify param http source (Raymond Feng)

2016-03-15, Version 1.11.0

  • Upgrade deps (Raymond Feng)

  • Switch to jsonpath-plus (Raymond Feng)

  • This should fix issue #21 'Delete api not working' (Jouke Visser)

  • use an error object (Horia Radu)

  • handle http status code >= 4XX as errors (Horia Radu)

2016-02-19, Version 1.10.2

  • Remove sl-blip from dependencies (Miroslav Bajtoš)

  • Remove example dir (Simon Ho)

  • Refer to licenses with a link (Sam Roberts)

  • Use strongloop conventions for licensing (Sam Roberts)

2015-09-18, Version 1.10.1

  • Relax the test so that it matches both ave and avenue (Raymond Feng)

2015-07-10, Version 1.10.0

  • Use JSON.parse for default json values (Raymond Feng)

2015-05-27, Version 1.9.0

  • Add connector hooks (Raymond Feng)

2015-05-15, Version 1.8.1

  • fix issue #29 (MuSTa1nE)

2015-04-20, Version 1.8.0

  • Add bluebird as a dev dep (Raymond Feng)

  • Fix the assertions (Raymond Feng)

  • add promise support for rest-builder invoke method (Esco Obong)

2015-03-17, Version 1.7.0

  • Clean up the comments (Raymond Feng)

  • Remove commented out code (Raymond Feng)

  • Allow vars in keys for the template (Raymond Feng)

  • add lodash and merge defaults in order of precedence (Bryan Clark)

2015-02-23, Version 1.6.0

  • Upgrade deps (Raymond Feng)

  • Fix/workaround the test failure (Raymond Feng)

  • Fix bad CLA URL in CONTRIBUTING.md (Ryan Graham)

2014-11-27, Version 1.5.0

  • Add tests (Raymond Feng)

  • Allow options to be configured for request module (Raymond Feng)

2014-11-27, Version 1.4.1

  • Fix failing tests (Raymond Feng)

2014-10-06, Version 1.4.0

  • Bump version (Raymond Feng)

  • Add contribution guidelines (Ryan Graham)

  • Fix the samples to support LB 2.x (Raymond Feng)

  • Changed to propogate settings into rest-builder in order to support clientCert+Key (Shelby Sanders)

2014-09-26, Version 1.3.1

  • Update deps (Raymond Feng)

  • updateAttributes was double wrapping the callback in this.responseHandler causing it to be called twice which unexpected response parameter. (Arash Malekzadeh)

2014-08-29, Version 1.3.0

  • Bump version (Raymond Feng)

  • Upgrade to express 4.x (Raymond Feng)

  • Add connector type (Raymond Feng)

  • improve property existence test (Clark Wang)

  • Add form support to request builder (Clark Wang)

  • Allow to force json (Clark Wang)

  • Support specifying rest resource name (Lance Hudson)

2014-07-09, Version 1.2.1

  • Remove peer dep on loopback-datasource-juggler (Miroslav Bajtoš)

  • Update link to doc (Rand McKinney)

  • Reformat the code (Raymond Feng)

  • Add debug, derive http verb from the template (Raymond Feng)

2014-03-12, Version 1.1.4

  • Update dependencies and bump version (Raymond Feng)

  • Update to dual MIT/StrongLoop license (Raymond Feng)

  • Adds support for processors (Raymond Feng)

  • Replace old README with link to docs. (Rand McKinney)

  • Remove some of the dev deps for framework comparison examples (Raymond Feng)

  • Upgrade dependencies (Raymond Feng)

2013-12-06, Version 1.1.3

  • Bump version (Raymond Feng)

  • Update deps (Raymond Feng)

  • Update docs.json (Rand McKinney)

  • Fix the ref to Text type (Raymond Feng)

  • Remove blanket (Raymond Feng)

  • Bump version and update dependencies (Raymond Feng)

  • Fix package.json due to merging mistake (Raymond Feng)

  • Reset git dep (Raymond Feng)

2013-09-11, Version strongloopsuite-1.0.0-5

2013-09-11, Version strongloopsuite-1.0.0-4

2013-09-11, Version strongloopsuite-1.0.0-3

  • Add keywords to package.json (Raymond Feng)

2013-09-10, Version strongloopsuite-1.0.0-2

  • Capture more information to the error object (Raymond Feng)

  • Build an error ojbect only if err is not present (Raymond Feng)

  • Build an Error object (Raymond Feng)

  • Set up status code (Raymond Feng)

  • Finalize package.json for sls-1.0.0 (Raymond Feng)

  • Fix the test failure for not found (Raymond Feng)

  • Changed tag to strongloopsuite-1.0.0-2 (cgole)

2013-09-05, Version strongloopsuite-1.0.0-1

2013-09-05, Version strongloopsuite-1.0.0-0

  • Updated to use tagged version strongloopsuite-1.0.0-0 of dependencies (cgole)

2013-09-04, Version 1.2.0

  • First release!