3

How to create an external API on Loopback?

I want to get the external API data and use it on my loopback application, and also pass the input from my loopback to external API and return result or response.

2 Answers 2

5

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.

If you post details on the API call(s) you want to call then I can add some more specific code samples for you. In the mean time, this is also from the documentation:

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"]
      }
    }
  ]
}

You could then call this api from code with:

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

1
  • Hi conradj, thank for reply. ya i got it. thank you very much
    – php_dvp
    Dec 9, 2015 at 6:37
1

You gonna need https module for calling external module inside loopback.

Suppose you want to use the external API with any model script file. Let the model name be Customer

Inside your loopback folder. Type this command and install https module.

$npm install https --save

common/models/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"
    }
)

common/models/customer.json

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

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

Now explore the api at /api/modelName/extenalApiProcessing

By default its a post method.

For more info. Loopback Remote Methods

3
  • @yongpin seems you are new on StackOverflow. Welcome to StackOverflow. Whenever you got the answer you were looking for then click the green tick mark to make it the correct answer. So that other may find it useful too. Dec 7, 2015 at 13:15
  • Hi Robin, thank for replied. I have followed you methods, but i still get the error, beside this three files, what i still need to do? This is the error i get. fn.accepts.push({arg: p, type: args[p].type, ^ TypeError: Cannot read property 'type' of undefined
    – php_dvp
    Dec 8, 2015 at 2:12
  • Post me ur complete. Error u get and ur code what you have tried so far Dec 8, 2015 at 3:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.