How do I make an API call inside a Firebase Cloud Function?

Viewed 587

I'm trying to create a Firebase Cloud Function where I make an API call to NewsAPI and retrieve a set of articles. The code below is an example, and it aims to retrieve articles from BBCNews.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

var url = 'http://newsapi.org/v2/top-headlines?' +
  'sources=bbc-news&' +
  'apiKey={myKey}';

const GetArticles = () => (
  fetch(new Request(url))
    .then(function (response) {
      console.log(response.json());
    })
);

When I run this code I get the following error message:

ReferenceError: Request is not defined
    at Object.<anonymous> (C:\Kesav\Coding stuff\project-academy\functions\index.js:9:11)
    at Module._compile (internal/modules/cjs/loader.js:1185:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1205:10)
    at Module.load (internal/modules/cjs/loader.js:1034:32)
    at Function.Module._load (internal/modules/cjs/loader.js:923:14)
    at Module.require (internal/modules/cjs/loader.js:1074:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at C:\Users\kkosa\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:661:33
    at Generator.next (<anonymous>)
    at fulfilled (C:\Users\kkosa\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:5:58)

How would I fix this?

1 Answers

You apparen't don't have any code that imports Request. That's not a "free object" in nodejs. You're going to have to find an HTTP client library for node (you have many options), import it, and use that in your code.

Related