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

AFL0831

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.

Kingsley Zhong

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Getting the "videoId" from a YouTube video using YouTubeV3-API

Getting video id "Live Stream" from Youtube

trying to extract video id from json using youtube api

Getting search results for a category from the YouTube API

Youtube API get Google+ ID from Youtube User Name

Search video with YouTube API on Android

Uploded Video using Youtube rest API getting Failed

youtube api video search using php restrict adult videos

Getting "Time Elapsed" of a playing video from the YouTube API in ActionScript 3.0

How can I get a Youtube video ID from the Youtube API given the video url?

Youtube API - Display most recently uploaded video from a specific user

getting the youtube id from a link

Search youtube channel for specific video id's

Youtube search using the google API

C# Using Youtube API - How do I check the last time a particular user uploaded a video to Youtube?

Getting 400 when uploading video with YouTube API

YouTube API - Search for video in specific channel

Youtube video id (or URL) to "user" and "channel"

How to get thumbnail of youtube video from url using php and API

Search Youtube video by Keyword using Java

scrape YouTube video from a specific channel and search?

Access Youtube Video URL or ID in MediaWiki API

Get youtube video id from youtube url in smarty template?

Fetch YouTube Video Id from youtube URL in zend framework

Is any way to rate the youtube video using any google or youtube API?

Youtube Player View not displaying video using with youtube API and channel import

how to "add participants" for private youtube video using youtube api

How to mute a Youtube Video by using Youtube API v3?

Retrieving youtube video location tag using youtube API 3.0