Call Get YouTube Playlist with Firebase Functions | Real-life API Example Instructions and Code Copy

CR Rollyson
3 min readMar 21, 2020

General Starting Testing Advice:

Go step by step

Assuming you can confirm a successful get request via a direct browser test or an API testing app like Postman (it rules), get started by flowing into the functions index.js file.

Requirements: Your project needs a Firebase Blaze plan in order to make external API requests. It’s literally pennies a month for my portfolio site. Be sure to set alerts for pricing just to be safe.

Note: I’m using npm-rest-client to automate the manual processing of parsing returned data into an object. You’ll need to add this package via command line interface if you choose to directly copy/paste this. There is a native, low-level https module included in Node.js, but it does not support promises. Learn more about it here.

LET’S CODE:

Start in functions/index.js:

// firebase init
const
functions = require(‘firebase-functions’);
const admin = require(‘firebase-admin’);
admin.initializeApp();

// npm-rest-client init
const Client = require(‘node-rest-client’).Client;
const clientYT = new Client();

// youtube URL Endpoint (note params to be modified — your playlistId & key)
const
YT_URL = ‘https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId={Your Playlist ID}&fields=items(snippet(description%2Ctitle%2CresourceId(videoId)))&key={YourDeveloperAPIKey}’;

// firebase exports to make youtube request
exports.fetchyoutube = functions.https.onRequest((req, res) => { clientYT.get(YT_URL, function(data, response) {
return res.status(200)
.type(‘application/json’)
.send(data);
}); // end get

}); // end export

Deploy Firebase Functions from CLI:

$ firebase deploy

Test returned URL from firebase CLI success message:

Will look something like this:
https://cloudfunctionslocation-projectname.cloudfunctions.net/fetchyoutube

ON SUCCESS:

When successful, you’ll see a returned object in the browser window similar to this:

Screenshot for Medium crrollyson.com — Get YouTube Playlist with Firebase Functions — Real Life Example

ON ERROR:

If you receive an error, start reviewing with the easy things first:

  1. Check for transposed errors— spelling or coding errors
  2. Check URL endpoint — verify the original test is working and that the URL is the same in your functions/index.js call
  3. Check firebase functions dashboard health error console — https://console.firebase.google.com/project/projectname/functions/health

If you continue to have errors, add a comment below — I’ve likely experienced it and happy to help.

NEXT STEPS:

Get Organized

Leverage Firebase environment functions:config() to set your keys and private developer information. This allows you to maintain organization, separate concerns, and follow proper storage of private information.

firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"

My firebase functions config for this youtube api looks like this:

{
“youtube”: {
“api”: {
“fields”: “items(snippet(description%2Ctitle%2CresourceId(videoId)))”,
“url”: “https://www.googleapis.com/youtube/v3/playlistItems”
},
“crytp”: {
“key”: “secret project key not listed here”
},
“portfolioplaylist”: {
“id”: “PL3E_131mdhVOTKRCamI36uXNq3eyhfwAB”
}

  • youtube.api | I’ve added the URL and fields parameter to more easily construct my YT_URL in my GET request. When the YouTube endpoint parameters or my requirements change, I can update easily in the config.
  • youtube.crytp | crytp is how I’m identifying this specific project (cr = my project identifier, yt = youtube, p = player). Good idea to plan for scaling. If I want to add another project, there will be no ‘key’ conflict.
  • youtube.portfolioplaylist | I’ve named this to be clearly identifiable. It’s a playlist that holds my portfolio videos. Also good idea to plan ahead for scaling. If I want to add another type of youtube request, there will be no ‘id’ conflict. I can also add additional information about the portfolio playlist–managing in one spot.

LET’S REBUILD THE YT_URL

Now that we have separated our concerns and coding logic, let’s turn that long URL into something more easily manageable.

Start by commenting out the existing (working) URL. Then rebuild it by leveraging your newly minted environment functions config:

const YT_URL = functions.config().youtube.api.url + ‘?part=snippet&maxResults=50&playlistId=’ + functions.config().youtube.portfolioplaylist.id + ‘&fields=’ + functions.config().youtube.api.fields + ‘&key=’ + functions.config().youtube.crytp.key;

Deploy Firebase Functions from CLI:

$ firebase deploy

Test returned URL from firebase CLI success message:

Will look something like this:
https://cloudfunctionslocation-projectname.cloudfunctions.net/fetchyoutube

View It In Action:

View in use on my site here: https://crrollyson.com/videos.html

If you found this helpful, like > follow > share > comment.

CR Rollyson is a Digital User Experience & Web Manager for a S&P 500 Fintech company and is the COO of Side Role, a marketing team in Charlotte North Carolina partnering with In-house Teams & Agencies, Non-profits, and Start-Ups. Learn more about Side Role here.

--

--

CR Rollyson

UX & Web mgr for a S&P 500 Fintech & COO of Side Role, a marketing team partnering w In-house Teams & Agencies, Non-profits, & Start-Ups. https://siderole.com