Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting YouTube Video ID from user-supplied search term using YouTube API

Very new beginner here. I'm currently working on a project where a user can enter a search term and, using the YouTube Data API v3, get a video ID. This video ID is then used to assemble a URL which I'm then using to have the video downloaded to my computer. Here's what I'm using to do that. (Ignore the libraries that I have imported, I'll get those cleaned up later)

from __future__ import print_function
import pathlib
from pathlib import Path
import pytube
import os
import os.path
import googleapiclient
import google_auth_httplib2
import google_auth_oauthlib
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from pytube import YouTube



import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
userVideoChoice=input("Please enter the title of the song you want to use. ")
def main():
    
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = ("CLIENT SECRET FILE HERE")

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.search().list(
        part="snippet",
        maxResults=1,
        q=userVideoChoice
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

So, for a search query of "Youtube Rewind 2018", the Youtube API would return this:

{'kind': 'youtube#searchListResponse', 'etag': 'HEbvpHREbTpRzcvryx2ubH2tnDo', 'nextPageToken': 'CAEQAA', 'regionCode': 'US', 'pageInfo': {'totalResults': 1000000, 'resultsPerPage': 1}, 'items': [{'kind': 'youtube#searchResult', 'etag': 'VX4FEWIWXekE8cUP4SCMNhGl7Ek', 'id': {'kind': 'youtube#video', 'videoId': 'YbJOTdZBX1g'}, 'snippet': {'publishedAt': '2018-12-06T17:58:29Z', 'channelId': 'UCBR8-60-B28hp2BmDPdntcQ', 'title': 'YouTube Rewind 2018: Everyone Controls Rewind | #YouTubeRewind', 'description': "YouTube Rewind 2018. Celebrating the videos, people, music and moments that defined 2018. #YouTubeRewind It wouldn't be Rewind without the creators: ...", 'thumbnails': {'default': {'url': 'https://i.ytimg.com/vi/YbJOTdZBX1g/default.jpg', 'width': 120, 'height': 90}, 'medium': {'url': 'https://i.ytimg.com/vi/YbJOTdZBX1g/mqdefault.jpg', 'width': 320, 'height': 180}, 'high': {'url': 'https://i.ytimg.com/vi/YbJOTdZBX1g/hqdefault.jpg', 'width': 480, 'height': 360}}, 'channelTitle': 'YouTube', 'liveBroadcastContent': 'none', 'publishTime': '2018-12-06T17:58:29Z'}}]}

What I'm trying to do is isolate the 'videoId' string which I'll then use to assemble a URL. I feel like there's a pretty simple solution out there that I'm not seeing as a beginner programmer. Can I get some help isolating this part that I need to continue with my project?

Thank you in advance for all of your help.

like image 408
AFL0831 Avatar asked Sep 08 '25 04:09

AFL0831


1 Answers

Since response is a dictionary, you can access it's elements through indices. response[items] is a list so it's best to iterate through all the items in that list. With this we can generate a list of video_ids as follows:

video_ids = []
for item in response['items']:
    video_ids.append(item['id']['videoId'])

print(video_ids)

This code goes under request.execute()

As a side-note, dictonaries are a lot easier to understand by using PrettyPrinter. I would add something like

import pprint
pp = pprint.PrettyPrinter(indent=2).pprint

at the end of your imports and use pp(response) instead of print(response).

like image 179
Kingsley Zhong Avatar answered Sep 09 '25 20:09

Kingsley Zhong