Tobi
Tobi

Reputation: 1902

How to fetch a URL with Google Cloud functions? request?

I used Google Apps Script with

var response = UrlFetchApp.fetch(url, params);

to get a response from an api. Sadly its too many request and too many data i need to be handled with Google Apps Script in Drive

My idea was now to switch to Google cloud functions and request but its not working.

const request = require('request');

const headers = {
    "Authorization" : "Basic " + Buffer.from('blabla').toString('base64')
};

const params = {
    "method":"GET",
    "headers":headers
};

exports.getCheckfrontBookings = (req, res) => {
  let url = 'https://fpronline.checkfront.com/api/3.0/item'

  request({url:url, qs:params}, function(err, response, body) {
    if(err) { console.log(err); return; }
    console.log("Get response: " + response.statusCode);
  });

Upvotes: 3

Views: 2915

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

request supports callback interfaces natively but does not return a promise, which is what you must do within a Cloud Function.

You could use request-promise (https://github.com/request/request-promise) and the rp(...) method which "returns a regular Promises/A+ compliant promise" and then do something like:

const rp = require('request-promise');

exports.getCheckfrontBookings = (req, res) => {

  var options = {
    uri: 'https://fpronline.checkfront.com/api/3.0/item',
    headers: {
      Authorization: 'Basic ' + Buffer.from('blabla').toString('base64')
    },
    json: true // Automatically parses the JSON string in the response
  };

  rp(options)
    .then(response => {
      console.log('Get response: ' + response.statusCode);
      res.send('Success');
    })
    .catch(err => {
      // API call failed...
      res.status(500).send('Error': err);
    });
};

Upvotes: 2

Related Questions