youtubeAPIspython
Ben Gorman

Ben Gorman

Life's a garden. Dig it.

Challenge

Use the YouTube Data API to fetch the list of tags for the video How Hard Can You Hit a Golf Ball? (at 100,000 FPS) - Smarter Every Day 216 by Smarter Every Day.

Bonus Challenge

Use an environment variable to obfuscate your API key so that it's not embedded in your code.


Solution

['Smarter',
 'Every',
 'Day',
 ...
 'mark rober',
 'rocket club',
 'vacuum cannon']

Steps

  1. Get the video's id from the URL

    https://www.youtube.com/watch?v={==JT0wx27J9xs==}
  2. Call the videos.list endpoint with part=snippet and id=JT0wx27J9xs

  3. The list of tags will be nested in the response here :material-arrow-down:

    response['items'][0]['snippet']['tags']

Code

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)
 
# ...