[Python] I tried to get various information using YouTube Data API!

Introduction

Now that I have a chance to touch the YouTube Data API, I would like to summarize the information.

What is the YouTube Data API?

https://developers.google.com/youtube/v3/docs

With the API provided by YouTube, you can get information such as videos and channels and use it on your website or application. Please note that the upper limit of API usage (quota) per day is 10000.

Get the API key

Create a project on Google Cloud Platform

From here (https://console.cloud.google.com/projectcreate?hl=ja) Create a project.

The project name is arbitrary, ** Don't forget to change the project ID. ** **

プロジェクトの作成

Enable YouTube Data API v3

Enable the YouTube Data API because it will be used in the created project.

From here Valid after selecting a project To.

APIを有効にする

Creating credentials

From here (https://console.cloud.google.com/apis/api/youtube.googleapis.com/credentials?hl=ja) Create an API key.

API キーの作成

Make a note of the API key you created, as it will be used when you actually use the API.

Try to get various information with YouTube Data API

Install the required packages

Use pyenv to change the version of python.

$ pyenv install 3.8.3
$ pyenv local 3.8.3

Install the package to use the YouTube Data API.

$ pip install google-api-python-client==1.9.3

Search YouTube channel information

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

from apiclient.discovery import build

API_KEY = '<Enter the API key you got last time>'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
SEARCH_TEXT = '<Channel name you want to search>'

youtube = build(
    YOUTUBE_API_SERVICE_NAME,
    YOUTUBE_API_VERSION,
    developerKey=API_KEY
)

response = youtube.search().list(q=SEARCH_TEXT, part='id,snippet', maxResults=25).execute()

for item in response.get('items', []):
    if item['id']['kind'] != 'youtube#channel':
        continue
    print('*' * 10)
    print(json.dumps(item, indent=2, ensure_ascii=False))
    print('*' * 10)

↓ The result looks like this ↓

**********
{
  "kind": "youtube#searchResult",
  "etag": "jjisWD5m1O7aBCLstjwy_ldRnf4",
  "id": {
    "kind": "youtube#channel",
    "channelId": "UCTmRAt3wuYY8W5z9j9va97Q"
  },
  "snippet": {
    "publishedAt": "2017-12-13T04:47:03Z",
    "channelId": "UCTmRAt3wuYY8W5z9j9va97Q",
    "title": "Yahoo!Developer network",
    "description": "Yahoo! JAPAN Technology channel produced by Yahoo! JAPAN.",
    "thumbnails": {
      "default": {
        "url": "https://yt3.ggpht.com/-ZUW9jc79uzQ/AAAAAAAAAAI/AAAAAAAAAAA/LWM2XNvQPmI/s88-c-k-no-mo-rj-c0xffffff/photo.jpg "
      },
      "medium": {
        "url": "https://yt3.ggpht.com/-ZUW9jc79uzQ/AAAAAAAAAAI/AAAAAAAAAAA/LWM2XNvQPmI/s240-c-k-no-mo-rj-c0xffffff/photo.jpg "
      },
      "high": {
        "url": "https://yt3.ggpht.com/-ZUW9jc79uzQ/AAAAAAAAAAI/AAAAAAAAAAA/LWM2XNvQPmI/s800-c-k-no-mo-rj-c0xffffff/photo.jpg "
      }
    },
    "channelTitle": "Yahoo!Developer network",
    "liveBroadcastContent": "none",
    "publishTime": "2017-12-13T04:47:03Z"
  }
}
**********

Get more information on YouTube channels

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

from apiclient.discovery import build

API_KEY = '<Enter the previously obtained API key>'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
CHANNEL_ID = '<Last acquired channel ID>'

youtube = build(
    YOUTUBE_API_SERVICE_NAME,
    YOUTUBE_API_VERSION,
    developerKey=API_KEY
)

response = youtube.channels().list(
    part = 'snippet,statistics',
    id = CHANNEL_ID
    ).execute()

for item in response.get("items", []):
    if item["kind"] != "youtube#channel":
        continue
    print('*' * 10)
    print(json.dumps(item, indent=2, ensure_ascii=False))
    print('*' * 10)

↓ The result looks like this ↓

**********
{
  "kind": "youtube#channel",
  "etag": "itHsa0qDp15obMLvkpN6HnFjF_M",
  "id": "UCTmRAt3wuYY8W5z9j9va97Q",
  "snippet": {
    "title": "Yahoo!Developer network",
    "description": "Yahoo! JAPAN Technology channel produced by Yahoo! JAPAN.",
    "customUrl": "yahoodevelopernetworkjp",
    "publishedAt": "2017-12-13T04:47:03Z",
    "thumbnails": {
      "default": {
        "url": "https://yt3.ggpht.com/a/AATXAJzznTJCL9uFV63JvRtbeYwgzur7mwoqtPRQvg=s88-c-k-c0xffffffff-no-rj-mo",
        "width": 88,
        "height": 88
      },
      "medium": {
        "url": "https://yt3.ggpht.com/a/AATXAJzznTJCL9uFV63JvRtbeYwgzur7mwoqtPRQvg=s240-c-k-c0xffffffff-no-rj-mo",
        "width": 240,
        "height": 240
      },
      "high": {
        "url": "https://yt3.ggpht.com/a/AATXAJzznTJCL9uFV63JvRtbeYwgzur7mwoqtPRQvg=s800-c-k-c0xffffffff-no-rj-mo",
        "width": 800,
        "height": 800
      }
    },
    "localized": {
      "title": "Yahoo!Developer network",
      "description": "Yahoo! JAPAN Technology channel produced by Yahoo! JAPAN."
    },
    "country": "JP"
  },
  "statistics": {
    "viewCount": "7471",
    "commentCount": "0",
    "subscriberCount": "157",
    "hiddenSubscriberCount": false,
    "videoCount": "12"
  }
}
**********

Get information on videos published by YouTube channels

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

from apiclient.discovery import build

API_KEY = '<Enter the previously obtained API key>'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
CHANNEL_ID = '<Previously obtained channel ID>'

youtube = build(
    YOUTUBE_API_SERVICE_NAME,
    YOUTUBE_API_VERSION,
    developerKey=API_KEY
)

response = youtube.search().list(
    part = "snippet",
    channelId = CHANNEL_ID,
    maxResults = 1,
    order = "date" #Sort by date
    ).execute()

for item in response.get("items", []):
    if item["id"]["kind"] != "youtube#video":
        continue
    print('*' * 10)
    print(json.dumps(item, indent=2, ensure_ascii=False))
    print('*' * 10)

↓ The result looks like this ↓

**********
{
  "kind": "youtube#searchResult",
  "etag": "CtC0g1Ocx7pK6H8Yhd3hGS5z3uY",
  "id": {
    "kind": "youtube#video",
    "videoId": "vd3YVCtW-LY"
  },
  "snippet": {
    "publishedAt": "2020-02-20T06:02:39Z",
    "channelId": "UCTmRAt3wuYY8W5z9j9va97Q",
    "title": "Screen transition design using the new HTML portal ~ PayPay Mall and Yahoo!With an example of news ~/ Developers Summit 2020 14-A-2",
    "description": "Video of the session at Developers Summit 2020. Describes the portal. Click here for an overview of the stage https://event.shoeisha.jp/devsumi/20200213/session/2384/...",
    "thumbnails": {
      "default": {
        "url": "https://i.ytimg.com/vi/vd3YVCtW-LY/default.jpg ",
        "width": 120,
        "height": 90
      },
      "medium": {
        "url": "https://i.ytimg.com/vi/vd3YVCtW-LY/mqdefault.jpg ",
        "width": 320,
        "height": 180
      },
      "high": {
        "url": "https://i.ytimg.com/vi/vd3YVCtW-LY/hqdefault.jpg ",
        "width": 480,
        "height": 360
      }
    },
    "channelTitle": "Yahoo!Developer network",
    "liveBroadcastContent": "none",
    "publishTime": "2020-02-20T06:02:39Z"
  }
}
**********

Get detailed information about the video

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

from apiclient.discovery import build

API_KEY = '<Enter the previously obtained API key>'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
CHANNEL_ID = '<Previously obtained channel ID>'
VIDEO_ID_LIST = ['<Last acquired video ID>']

youtube = build(
    YOUTUBE_API_SERVICE_NAME,
    YOUTUBE_API_VERSION,
    developerKey=API_KEY
)

for video_id in VIDEO_ID_LIST:
    response = youtube.videos().list(
      part = 'snippet,statistics',
      id = video_id
      ).execute()

    for item in response.get("items", []):
        if item["kind"] != "youtube#video":
            continue
        print('*' * 10)
        print(json.dumps(item, indent=2, ensure_ascii=False))
        print('*' * 10)

↓ The result looks like this ↓

**********
{
  "kind": "youtube#video",
  "etag": "Y5QH8Ur-9BQigbr4XHTRNldn7_I",
  "id": "vd3YVCtW-LY",
  "snippet": {
    "publishedAt": "2020-02-20T06:02:39Z",
    "channelId": "UCTmRAt3wuYY8W5z9j9va97Q",
    "title": "Screen transition design using the new HTML portal ~ PayPay Mall and Yahoo!With an example of news ~/ Developers Summit 2020 14-A-2",
    "description": "Video of the session at Developers Summit 2020.\Describes nportal.\n\n Click here for an overview of the stage\nhttps://event.shoeisha.jp/devsumi/20200213/session/2384/\n\n Click here for materials\nhttps://www.slideshare.net/techblogyahoo/htmlportal-paypayyahoo-devsumi",
    "thumbnails": {
      "default": {
        "url": "https://i.ytimg.com/vi/vd3YVCtW-LY/default.jpg ",
        "width": 120,
        "height": 90
      },
      "medium": {
        "url": "https://i.ytimg.com/vi/vd3YVCtW-LY/mqdefault.jpg ",
        "width": 320,
        "height": 180
      },
      "high": {
        "url": "https://i.ytimg.com/vi/vd3YVCtW-LY/hqdefault.jpg ",
        "width": 480,
        "height": 360
      }
    },
    "channelTitle": "Yahoo!Developer network",
    "tags": [
      "devsumi",
      "devsumiA",
      "Portals"
    ],
    "categoryId": "28",
    "liveBroadcastContent": "none",
    "defaultLanguage": "ja",
    "localized": {
      "title": "Screen transition design using the new HTML portal ~ PayPay Mall and Yahoo!With an example of news ~/ Developers Summit 2020 14-A-2",
      "description": "Video of the session at Developers Summit 2020.\Describes nportal.\n\n Click here for an overview of the stage\nhttps://event.shoeisha.jp/devsumi/20200213/session/2384/\n\n Click here for materials\nhttps://www.slideshare.net/techblogyahoo/htmlportal-paypayyahoo-devsumi"
    },
    "defaultAudioLanguage": "ja"
  },
  "statistics": {
    "viewCount": "74",
    "likeCount": "2",
    "dislikeCount": "0",
    "favoriteCount": "0",
    "commentCount": "0"
  }
}
**********

at the end

How was that? There are many other articles published on Code Samples, so please take a look and try them out. If you find something wrong, please comment mm

Recommended Posts

[Python] I tried to get various information using YouTube Data API!
I tried to search videos using Youtube Data API (beginner)
I tried using YOUTUBE Data API V3
Get Youtube data in Python using Youtube Data API
I tried to get various information from the codeforces API
[Python] Get all comments using Youtube Data API
I tried to get CloudWatch data with Python
I tried to get the movie information of TMDb API with Python
I tried to get Web information using "Requests" and "lxml"
[Python] I tried collecting data using the API of wikipedia
I tried to get data from AS / 400 quickly using pypyodbc
I tried using UnityCloudBuild API from Python
I tried to get data from AS / 400 quickly using pypyodbc Preparation 1
How to get article data using Qiita API
Get information about videos uploaded to YouTube [Python]
I tried to get the authentication code of Qiita API with Python.
I tried to summarize various sentences using the automatic summarization API "summpy"
I tried fMRI data analysis with python (Introduction to brain information decoding)
[Rails] How to get location information using Geolocation API
I tried to get started with blender python script_Part 01
Get Youtube data with python
Get LEAD data using Marketo's REST API in Python
Python programming: I tried to get (crawling) news articles using Selenium and BeautifulSoup4.
I tried to get started with blender python script_Part 02
[Python] Get insight data using Google My Business API
I tried to get an AMI using AWS Lambda
[Python] I tried using OpenPose
I tried to analyze J League data with Python
[Python] I tried to get Json of squid ring 2
Python programming: I tried to get company information (crawling) from Yahoo Finance in the US using BeautifulSoup4
I tried to access Google Spread Sheets using Python
I tried to extract various information of remote PC from Python by WMI Library
I tried scraping food recall information with Python to create a pandas data frame
I tried to get the location information of Odakyu Bus
I tried to create API list.csv in Python from swagger.yaml
I tried various methods to send Japanese mail with Python
I tried to make a stopwatch using tkinter in python
I tried to analyze scRNA-seq data using Topological Data Analysis (TDA)
Output product information to csv using Rakuten product search API [Python]
Play with YouTube Data API v3 using Google API Python Client
Call github api in python to get pull request information
Get Salesforce data using REST API
I tried to create Quip API
I tried to touch Python (installation)
Get Amazon data using Keep API # 1 Get data
I tried using Thonny (Python / IDE)
I tried to touch Tesla's API
I tried using the checkio API
[Python] I tried using YOLO v3
I tried to get a database of horse racing using Pandas
I tried to get the index of the list using the enumerate function
I tried to make a regular expression of "amount" using Python
How to get followers and followers from python using the Mastodon API
I tried to make a regular expression of "time" using Python
[Python] A memo that I tried to get started with asyncio
I tried to make a regular expression of "date" using Python
I tried to analyze my favorite singer (SHISHAMO) using Spotify API
[Pandas] I tried to analyze sales data with Python [For beginners]
Collect product information and process data using Rakuten product search API [Python]
I tried to get a list of AMI Names using Boto3
I tried to visualize BigQuery data using Jupyter Lab on GCP