Get the Latest Video of a YouTube Channel Using Cloud Functions for Firebase


firebase youtube api cloud

Hello! If you are from Ukraine, Belarus, Poland or India and looking for a job in Software Development, please reach me out by email.

Introduction

We will create a cloud function for Firebase that takes Youtube channelId as a query string and always redirects to the latest video of the passed Youtube channel. Why it can be useful? Many Instagram or other influencers manually paste the link to the latest video on their bio. This cloud function can simplify this process.

How it will work?

Diagram

  1. The Web/Mobile client makes GET HTTP request with channelID as a query parameter
  2. The function triggered
  3. The code inside function makes a query to Youtube API using googleapis. It will make one request that asks to return a list of channel’s video (ordered by date).
  4. The response from Youtube API will have an array with one object that represents the latest video on the specific Youtube channel
  5. The function sends 302 redirect to the video from the previous paragraph.

Prerequisites

Project Setup

  1. Let’s create a folder

    mkdir latestYTChannelVideo && cd latestYTChannelVideo
    
  2. Initialize Cloud Functions project for Firebase

    firebase init functions
    
  3. Select Create a new project or Use an existing project if you have an existing project

  4. Select Javascript as a language

  5. (Optional) Setup ESlint

  6. (Optional) Install dependencies with NPM

    After these actions, your project will be initialized

Setup dependencies

Because we are using Node@8 we need to specify the version of Node in functions/package.json

"engines": {
    "node": "8"
  },

Also, we need to install google-api-client to communicate with the Youtbe API. Do this in functions/ folder:

npm i googleapis --save

Our dependencies list will be the following:

  "dependencies": {
    "firebase-admin": "^8.10.0",
    "firebase-functions": "^3.6.1",
    "googleapis": "61.0.0"
  },

Import modules

Now we need to import all required modules. We will use firebase-functions module to handle HTTP request and googleapis to request Youtube API. Open functions/index.js and start editing it by adding:

const functions = require('firebase-functions');
const { google } = require('googleapis');

Initialize Youtube client

We will call google.youtube method with our Youtube API key. This method will return an instance with Youtube API methods:

const youtube = google.youtube({
    version: 'v3',
    auth: functions.config().youtube.key,
});

We will get the Youtube API key from Firebase Config. We will talk about this further.

Set environment configuration

firebase functions:config:set youtube.key="YOUTUBE API KEY"

Because we will run our function in the emulator we should get custom config (execute following within the functions directory)

firebase functions:config:get > .runtimeconfig.json

.runtimeconfig.json will appear in your functions/ dir and will contain the Youtube API key.

Add the latestYoutubeVideo() function

The following code will contain the whole function:

exports.latestYoutubeVideo = functions.https.onRequest(async (req, res) => {
    // Get channelId from query string
    const { channelId } = req.query;

    // Generate query to Youtube API
    // Get a list, ordered by date and limited to one item
    // Frankly, it's an array with 1 latest video
    const { data } = await youtube.search.list({
        part: 'id',
        order: 'date',
        channelId,
        maxResults: 1,
    });

    // Get ID object from items[0]  
    const { id } = data.items[0];

    // Get Video ID from Id object
    // Redirect to link with this video ID 
    return res.redirect(`https://www.youtube.com/watch?v=${id.videoId}`);
});

We get channelID from the query string, then pass it to youtube.search.list method. This method will get an array of videos for the YT channel that is ordered by date and limited to 1 item. Then we will get the ID object and get a videoId property from it and send redirect it to the video.

Run function locally

We will emulate our function by running firebase serve within functions/ folder:

Firebase serve

  1. In the output you can face a link to the function http function initialized (http://localhost:5000/blog-helpers/us-central1/latestYoutubeVideo)

  2. Paste it to the browser and add query string ?channelId=<some-youtube-channel-id>. As an example, you can use this value UCP4bf6IHJJQehibu6ai__cg. It is channel ID of an official Firebase Youtube Channel

  3. Press Enter in the address bar

  4. The browser will be redirected to the latest video on the Firebase channel

  5. In the logs you can observe the following picture:

    Logs

Completed code

You can review the completed code. This function will redirect to the latest Youtube video for the selected channel:

const functions = require('firebase-functions');
const { google } = require('googleapis');

const youtube = google.youtube({
    version: 'v3',
    auth: functions.config().youtube.key,
});

exports.latestYoutubeVideo = functions.https.onRequest(async (req, res) => {
    // Get channelId from query string
    const { channelId } = req.query;

    // Generate query to Youtube API
    // Get a list, ordered by date and limited to one item
    // Frankly, it's an array with 1 latest video
    const { data } = await youtube.search.list({
        part: 'id',
        order: 'date',
        channelId,
        maxResults: 1,
    });

    // Get ID object from items[0]
    const { id } = data.items[0];

    // Get Video ID from Id object
    // Redirect to link with this video ID
    return res.redirect(`https://www.youtube.com/watch?v=${id.videoId}`);
});
comments powered by Disqus