Loopback Connector REST API

时间:2015-12-07 10:13:55

标签: api loopbackjs

如何在Loopback上创建外部API?

我想获取外部API数据并在我的loopback应用程序中使用它,并将环回输入传递给外部API并返回结果或响应。

2 个答案:

答案 0 :(得分:4)

Loopback的概念为non-database connectors,包括REST connector。来自文档:

  

LoopBack支持许多连接到后端系统的连接器   数据库。

     

这些类型的连接器通常根据具体方法实现   在底层系统上。例如,REST连接器委托   在Push连接器与iOS和iOS集成时调用REST API   Android推送通知服务。

如果您发布了要调用的API调用的详细信息,那么我可以为您添加一些更具体的代码示例。与此同时,这也来自文档:

<强> datasources.json

MyModel": {
  "name": "MyModel",
  "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"]
      }
    }
  ]
}

然后您可以使用以下代码调用此api:

app.dataSources.MyModel.geocode('107 S B St', 'San Mateo', '94401', processResponse);

答案 1 :(得分:1)

你需要https模块来调用loopback中的外部模块。

假设您要将外部API与任何模型脚本文件一起使用。让模型名称为Customer

在你的loopback文件夹中。输入此命令并安装https模块。

$npm install https --save
  

公共/模型/ customer.js

var https = require('https');

Customer.externalApiProcessing = function(number, callback){
   var data = "https://rest.xyz.com/api/1";
   https.get(
     data,
     function(res) {
        res.on('data', function(data) {
          // all done! handle the data as you need to

          /*
             DO SOME PROCESSING ON THE `DATA` HERE
          */
enter code here
          //Finally return the data. the return type should be an object.
          callback(null, data);
        });
     }
   ).on('error', function(err) {
       console.log("Error getting data from the server.");
       // handle errors somewhow
       callback(err, null);
   }); 
  }




//Now registering the method
Customer.remoteMethod(
    'extenalApiProcessing', 
    {
      accepts: {arg: 'number', type: 'string', required:true},
      returns: {arg: 'myResponse', type: 'object'}, 
      description: "A test for processing on external Api and then sending back the response to /externalApiProcessing route"
    }
)
  

公共/模型/ customer.json

 ....
 ....
 //Now add this line in the ACL property.
 "acls": [

    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW",
      "property": "extenalApiProcessing"
    }
  ]

现在在/api/modelName/extenalApiProcessing

探索api

默认情况下为post method

了解更多信息。 Loopback Remote Methods