['Smarter',
'Every',
'Day',
...
'mark rober',
'rocket club',
'vacuum cannon']
Steps
Get the video's id from the URL
https://www.youtube.com/watch?v={==JT0wx27J9xs==}
Call the videos.list
endpoint with part=snippet
and id=JT0wx27J9xs
The list of tags will be nested in the response here :material-arrow-down:
response[ 'items' ][ 0 ][ 'snippet' ][ 'tags' ]
Code
Python
from googleapiclient.discovery import build
# Instantiate a googleapiclient.discovery.Resource object for youtube
youtube = build(
serviceName = 'youtube' ,
version = 'v3' ,
developerKey = 'YOURAPIKEY'
)
# Define the request
request = youtube.videos().list(
part = "snippet" ,
id = "JT0wx27J9xs"
)
# Execute the request and save the response
response = request.execute()
# Close the connection
youtube.close()
# Fetch the tags
item = response[ 'items' ][ 0 ]
item[ 'snippet' ][ 'tags' ]
Bonus Solution
It's bad practice to put API Key's in your code (for obvious reasons). One way around this is to store your API key in an environment variable. Then use the os
module to read it.
fetch_data.py
import os
from googleapiclient.discovery import build
# Get the API key from the YOUTUBE_API_KEY environment var
mykey = os.getenv[ "YOUTUBE_API_KEY" ]
# Instantiate a googleapiclient.discovery.Resource object for youtube
youtube = build( 'youtube' , 'v3' , developerKey = mykey)
# ...
You can set the environment variable when you execute the fetch_data.py
script.
bill@gates:~ $ YOUTUBE_API_KEY= "YOURAPIKEY" python fetch_data.py
Alternatively, you can store environment variables in a .env
file.
# environment variables defined inside a .env file
GCP_PROJECT_ID=my-project-id
YOUTUBE_API_KEY=YoUrApIkEy
and then load them with the dotenv
package.
fetch_data.py
import os
from dotenv import load_dotenv
from googleapiclient.discovery import build
# Load environment variables from .env
load_dotenv()
# Get the API key from the YOUTUBE_API_KEY environment var
mykey = os.getenv( "YOUTUBE_API_KEY" )
# Instantiate a googleapiclient.discovery.Resource object for youtube
youtube = build( 'youtube' , 'v3' , developerKey = mykey)
# ...