Youtube API to Get Upload Video List (Node.js)

July 26, 2021

Enable YouTube API and obtain credentials

Install dependencies

npm install googleapis --save
npm install google-auth-library --save

Code

const {google} = require('googleapis');

const GOOGLE_API_KEY = ...

// youtube username or channel id is required
// youtube username
// const username = ... 
// or youtube channel id
// https://www.youtube.com/channel/UCqK_GSMbpiV8spgD3ZGloSw
const channelId = 'UCqK_GSMbpiV8spgD3ZGloSw'

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

let res = null
let channelId = null
let playlistId = null

res = await youtube.channels.list({
  part: 'snippet,contentDetails', // ,statistics
  // forUsername: username,
  id: channelId,
  // headers: headers,
});

for (const channel of res.data.items) {
  console.log(channel.id, channel.snippet.title)
  // console.log(channel.contentDetails)
  // channelId = channel.id
  playlistId = channel.contentDetails.relatedPlaylists.uploads
}

let nextPageToken = null
let page = 1

while (page == 1 || nextPageToken) {
  res = await youtube.playlistItems.list({
    part: 'id,snippet,contentDetails', // ,
    playlistId: playlistId,
    pageToken: nextPageToken,
    maxResults: 20, // 50
    // headers: headers,
  });

  nextPageToken = res.data.nextPageToken

  const videos = res.data.items.map(video => {
    return {
      url: `https://www.youtube.com/watch?v=${video.contentDetails.videoId}`,
      title: video.snippet.title,
      date: new Date(video.snippet.publishedAt),
    }
  })

  video.forEach(video => {
    console.log(url, title, date)
  })

  page += 1
}

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.