Demo App — Part 2
Learn how to use the video and comment resources in a real-world app.
We'll cover the following
We’ve looked at the video
, commentThread
, and i18nRegion
resources and how we can use them to retrieve data from the API. We’ll integrate them into the project (YouTube Mini application) that we created earlier.
Workflow
Let’s build on our previous demo app “YouTube Mini.” We’ll integrate the following resources: video
, commentThread
, and i18nRegion
.
- We’ll create a filter for regions. Next to the search bar on the homepage, the user will have an option to search for videos associated with a particular keyword in a specific region. We’ll use the
i18nRegion
resource to retrieve the list of content regions, and then we’ll use the response data to populate the region filter. - Next to the “Channel Stats” button, we’ll have a button called “Video Stats”, which will use the
video
resource to retrieve the statistics and information of the particular video. - On the “Video Stats” page, we’ll use the
commentThread
resource to retrieve a list of top-level comments associated with that video.
Resources and methods used
This app uses the list
method for video
, commentThread
, and i18nRegion
resources from the API to retrieve the relevant data.
Run the app
Before running the app, let’s get an overview of the newly created functions and files that make the API calls and render the output.
We created three new functions in the views.py
file: get_regions
(line 22), get_comments
(line 65) and get_video_stats
(line 75). Each function makes an API call to retrieve regions, comments, and video statistics, respectively. We’ll display the data retrieved from the video
resource in a newly created video.html
file.
Ensure that all the API keys are set up correctly in the widget below to run the app. If you haven’t done so already, add the API key you generated for your project when you set up the credentials earlier. You can also change the value of the MAX_RESULTS
key to retrieve any number of results.
Now that everything is set up, let’s run the following code to experience integrating additional YouTube Data API resources in our app.
API_KEY = "{{API_KEY}}" MAX_RESULTS = {{MAX_RESULTS}} MAX_RESULTS_COMMENTS = 10 PART = "snippet" FIELDS = "kind,items(id,snippet(channelId,title,description,channelTitle))" api_service_name = "youtube" api_version = "v3" DEVELOPER_KEY = API_KEY youtube = googleapiclient.discovery.build( api_service_name, api_version, developerKey = DEVELOPER_KEY) def home(request): regionData = get_regions() print("Getting the regions...") final_list = {"data": regionData} return render(request,'index.html',context=final_list) def get_regions(): request = youtube.i18nRegions().list( part="snippet" ) response = request.execute() response["items"].sort(key=lambda x: x['snippet']['gl']) return response def get_channel_statistics(channelId): CHANNEL_ID = channelId # get channel statistics request = youtube.channels().list( part="snippet,statistics", id=CHANNEL_ID, fields="kind,items(kind,id,snippet(title,description),statistics)" ) response = request.execute() # get channel videos request_videos = youtube.search().list( part=PART, channelId=CHANNEL_ID, maxResults=MAX_RESULTS, type="video", fields=FIELDS ) response_videos = request_videos.execute() video_stats = get_video_stats(videoListData = response_videos) for i in range(len(response_videos["items"])): response_videos["items"][i]["videoData"] = video_stats[i] final_data = { "channelData": response, "videosData": response_videos } return final_data def get_comments(id): request = youtube.commentThreads().list( part="snippet,replies", maxResults=MAX_RESULTS_COMMENTS, videoId=id ) response = request.execute() return response def get_video_stats(videoListData="", videoId=""): data = "" if videoId != "": request = youtube.videos().list( part="snippet,statistics", id=videoId, fields = "kind,items(id,snippet(channelId,title,description,channelTitle),statistics)" ) response = request.execute() commentsData = "" try: commentsData = get_comments(videoId) except: print("This video has no comments!!!" ) data = {"videoData": response, "commentsData": commentsData} else: allVideos = [] for obj in videoListData["items"]: videoId = obj["id"]["videoId"] request = youtube.videos().list( part="snippet,statistics", id=videoId, fields = "kind,items(id,snippet(channelId,title,description,channelTitle),statistics)" ) response = request.execute() videoTitle = response["items"][0]["snippet"]["title"] videoStats = response["items"][0]["statistics"] videoData = {"title": videoTitle, "statistics": videoStats} allVideos.append(videoData) data = allVideos return data def get_search_list(query_str, region_code): if query_str is not None: request = youtube.search().list( part=PART, maxResults=MAX_RESULTS, q=query_str, type="video", fields=FIELDS, regionCode=region_code ) response = request.execute() video_stats = get_video_stats(videoListData = response) for i in range(len(response["items"])): response["items"][i]["videoData"] = video_stats[i] return response def buttonClick(request): query_str = request.POST.get("query_string") region_code = request.POST.get("region") print("Fetching Videos for the given string...") ## set default region code in case a user doesnot selects one if region_code == "": region_code = "US" search_list = get_search_list(query_str, region_code) regionData = get_regions() search_list = {"data": search_list, "regionData": regionData} return render(request,'searchPage.html',context=search_list) def buttonClickStats(request): channelId = request.POST.get('statsButton') print("Getting channel statistics...") final_data = get_channel_statistics(channelId) final_data = {"data": final_data} return render(request,'channel.html',context=final_data) def buttonClickStatsVideo(request): videoId = request.POST.get('videoStatsButton') print("Getting video statistics...") final_data = get_video_stats(videoId = videoId) final_data = {"data": final_data} return render(request,'video.html',context=final_data)