Gathering detailed insights and metrics for loopback-connector-rest
Gathering detailed insights and metrics for loopback-connector-rest
Gathering detailed insights and metrics for loopback-connector-rest
Gathering detailed insights and metrics for loopback-connector-rest
npm install loopback-connector-rest
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
75 Stars
336 Commits
82 Forks
60 Watching
24 Branches
38 Contributors
Updated on 17 Oct 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-5.6%
2,775
Compared to previous day
Last week
-0.7%
13,130
Compared to previous week
Last month
7.7%
59,825
Compared to previous month
Last year
-20.6%
793,490
Compared to previous year
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:
In your application root directory, enter:
1$ 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.
Use the data source generator to add a REST data source to your application.
For LoopBack 2.x:
1$ apic create --type datasource
For LoopBack 2.x or 3.0:
1$ 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:
1... 2 "myRESTdatasource": { 3 "name": "myRESTdatasource", 4 "connector": "rest" 5 } 6...
Create a LoopBack 4 DataSource with REST connector using the lb4 datasource
command.
Create a service that maps to the operations using the lb4 service
command.
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.
Configure the REST connector by editing datasources.json
manually (for example using the Google Maps API):
/server/datasources.json
1... 2"geoRest": { 3 "connector": "rest", 4 "debug": "false", 5 "operations": [{ 6 "template": { 7 "method": "GET", 8 "url": "http://maps.googleapis.com/maps/api/geocode/{format=json}", 9 "headers": { 10 "accepts": "application/json", 11 "content-type": "application/json" 12 }, 13 "query": { 14 "address": "{street},{city},{zipcode}", 15 "sensor": "{sensor=false}" 16 }, 17 "responsePath": "$.results[0].geometry.location" 18 }, 19 "functions": { 20 "geocode": ["street", "city", "zipcode"] 21 } 22 }] 23} 24...
The operations
property is an array of objects, each of which can have these properties:
template
: An object that defines a custom method using a template; see Defining a custom method using a template.functions
: An object that maps a JavaScript function to a list of parameter names.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.
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:
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
1{ 2 "connector": "rest", 3 "debug": false, 4 "options": { 5 "headers": { 6 "accept": "application/json", 7 "content-type": "application/json" 8 }, 9 "strictSSL": false 10 }, 11 "operations": [ 12 { 13 "template": { 14 "method": "GET", 15 "url": "http://maps.googleapis.com/maps/api/geocode/{format=json}", 16 "query": { 17 "address": "{street},{city},{zipcode}", 18 "sensor": "{sensor=false}" 19 }, 20 "options": { 21 "strictSSL": true, 22 "useQuerystring": true 23 }, 24 "responsePath": "$.results[0].geometry.location" 25 }, 26 "functions": { 27 "geocode": ["street", "city", "zipcode"] 28 } 29 } 30 ] 31}
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:
POST /users
GET /users/:id
DELETE /users/:id
PUT /users/:id
GET /users?limit=5&username=ray&order=email
For example:
/server/boot/script.js
1module.exports = function (app) { 2 var ds = app.loopback.createDataSource({ 3 connector: require("loopback-connector-rest"), 4 debug: false, 5 baseURL: "http://localhost:3000", 6 }); 7 8 var User = ds.createModel("user", { 9 name: String, 10 bio: String, 11 approved: Boolean, 12 joinedAt: Date, 13 age: Number, 14 }); 15 16 User.create( 17 new User({ 18 name: "Mary", 19 }), 20 function (err, user) { 21 console.log(user); 22 } 23 ); 24 25 User.find(function (err, user) { 26 console.log(user); 27 }); 28 29 User.findById(1, function (err, user) { 30 console.log(err, user); 31 }); 32 33 User.update( 34 new User({ 35 id: 1, 36 name: "Raymond", 37 }), 38 function (err, user) { 39 console.log(err, user); 40 } 41 ); 42};
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:
1var config = { 2 name: "ServiceTransaction", 3 base: "PersistedModel", 4 resourceName: "transactions", 5}; 6 7var 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'
.
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:
1template: { 2 "method": "GET", 3 "url": "http://maps.googleapis.com/maps/api/geocode/{format=json}", 4 "headers": { 5 "accepts": "application/json", 6 "content-type": "application/json" 7 }, 8 "query": { 9 "address": "{street},{city},{zipcode}", 10 "sensor": "{sensor=false}" 11 }, 12 "responsePath": "$.results[0].geometry.location" 13 }
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.1var loopback = require("loopback"); 2 3var ds = loopback.createDataSource({ 4 connector: require("loopback-connector-rest"), 5 debug: false, 6 operations: [ 7 { 8 template: { 9 method: "GET", 10 url: "http://maps.googleapis.com/maps/api/geocode/{format=json}", 11 headers: { 12 accepts: "application/json", 13 "content-type": "application/json", 14 }, 15 query: { 16 address: "{street},{city},{zipcode}", 17 sensor: "{sensor=false}", 18 }, 19 responsePath: "$.results[0].geometry.location", 20 }, 21 functions: { 22 geocode: ["street", "city", "zipcode"], 23 }, 24 }, 25 ], 26});
Now you can invoke the geocode API in Node.js as follows:
1Model.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:
1Model.invoke( 2 { street: "107 S B St", city: "San Mateo", zipcode: "94401" }, 3 processResponse 4);
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:
1{ 2 "template": { 3 "method": "POST", 4 "url": "http://localhost:3000/{p}", 5 "headers": { 6 "accept": "application/{format}" 7 }, 8 "query": { 9 "x": "{x}", 10 "y": 2 11 }, 12 "body": { 13 "a": "{a:number}", 14 "b": "{b=true}" 15 } 16 }, 17 "functions": { 18 "myOp": [ 19 "p", 20 "x", 21 "a", 22 { 23 "name": "b", 24 "source": "header" 25 } 26 ] 27 } 28}
For the template above, the variables will be mapped as follows:
Please note that path variables are appended to the path, for example, /myOp/:p.
No vulnerabilities found.
No security vulnerabilities found.