Building a YouTube Shorts Trending Viewer with Streamlit and the YouTube API
Day 4, Experiment #4
Just created a Streamlit app that searches for and retrieves the Top Trending Youtube Shorts using Youtube API.
How the App Works :
- Importing the necessary modules
import streamlit as st
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import json
- Reading the JSON file containing authorization information
To access the YouTube API, we need to authenticate with Google. We do this by reading a JSON file containing the necessary authorization information. We’ll store the path to this JSON file in a variable named json_file_path
.
# Path to the JSON file containing user's authorization information
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
json_file_path = "/path/to/client_secrets.json"
# Read the JSON file and convert it to a Python dictionary
with open(json_file_path, "r") as f:
json_data = f.read()
auth_info = json.loads(json_data)['web']
- Authenticating with Google and building the YouTube service using the credentials
# Pass the auth_info dictionary to the from_authorized_user_info method
creds = Credentials.from_authorized_user_info(info=auth_info, scopes=SCOPES)
# Define the authorization flow
flow = InstalledAppFlow.from_client_secrets_file(json_file_path, SCOPES)
creds = flow.run_local_server(port=0)
if not creds or not creds.valid:
# If the credentials are not valid, run the authorization flow
st.warning("Please authenticate with Google to continue.")
auth_url, _ = flow.authorization_url(prompt='consent')
st.write(f"Please go to this URL to authenticate: {auth_url}")
code = st.text_input("Enter the authorization code:")
if code:
try:
flow.fetch_token(code=code)
creds = flow.credentials
st.success("Authentication successful!")
except Exception as e:
st.error(f"Error fetching credentials: {e}")
else:
st.success("You are authenticated with Google!")
- Building the YouTube service using the credentials
Now that we have successfully authenticated with Google, we can now build the YouTube service using the credentials that we just obtained. We will use the build
function from the googleapiclient.discovery
module to create an instance of the YouTube service.
# Build the YouTube service using the credentials
try:
youtube = build('youtube', 'v3', credentials=creds)
except HttpError as e:
st.error(f"An error occurred: {e}")
st.stop()
Here, we are using the build
function to create an instance of the youtube
service. We are passing the parameters youtube
and v3
to specify that we want to use the YouTube Data API version 3. We are also passing the credentials
parameter to specify that we want to use the credentials we obtained earlier to authenticate with the API.
If there is an error building the service, we catch the HttpError
exception and display an error message using st.error()
. We then use st.stop()
to stop the Streamlit app.
- Requesting Trending YouTube Shorts
Now that we have successfully authenticated and built the YouTube service, we can start making requests to the YouTube API. In this section, we will request the most popular short videos on YouTube Shorts for a specific category.
We will use the youtube.search().list()
method to request the most popular short videos on YouTube Shorts for the specified category. Here's the code:
# Ask user to specify the specific category for the trending YouTube Shorts
category_id = st.selectbox("Please select a category ID from the list", ["10", "20", "30", "40", "50"])
# Request the most popular short videos on YouTube Shorts for the specified category
try:
request = youtube.search().list(
part='id',
type='video',
videoDuration='short',
videoCategoryId=category_id,
maxResults=10,
order='viewCount'
)
response = request.execute()
except HttpError as e:
st.error(f"An error occurred: {e}")
st.stop()
Next, we make a request to the search
method of the YouTube API to get the most popular short videos for the specified category. We pass the following parameters to the search().list()
method:
part
: specifies the parts of the resource that the API response should include. We are only interested in the video ID, so we setpart
to'id'
.type
: specifies the type of resource we want to search for. We are only interested in videos, so we settype
to'video'
.videoDuration
: specifies the duration of the videos we want to retrieve. We are only interested in short videos, so we setvideoDuration
to'short'
.videoCategoryId
: specifies the category ID of the videos we want to retrieve. We get this value from the user's selection in the previous step.maxResults
: specifies the maximum number of results we want to retrieve. We set this to 10.order
: specifies the order in which the search results should be returned. We want the results to be ordered by view count, so we setorder
to'viewCount'
.
If there is an error making the request, we catch the HttpError
exception and display an error message using st.error()
. We then use `st.stop()` to stop the script execution.
Once we have successfully made the request and received a response, we can extract the video titles and IDs from the response and display them to the user using st.write(). Here’s the code that does this:
if 'items' in response:
st.header("Trending YouTube Shorts")
for item in response['items']:
video_id = item['id']['videoId']
video_response = youtube.videos().list(
part='snippet',
id=video_id
).execute()
title = video_response['items'][0]['snippet']['title']
st.write(f"{title} - {video_id}")
else:
st.warning("No results found.")
We start by checking if there are any items in the response. If there are, we use a for loop to iterate through each item and extract the video ID using the ['id']['videoId']
notation. We then make another request to the YouTube API to get the video's title using the video ID. Finally, we display the video title and ID to the user using st.write().
If there are no items in the response, we display a warning message using st.warning().
And that’s it! We’ve built a simple Streamlit app that allows users to browse trending YouTube Shorts videos for a specific category.
In this article, we’ve covered how to :
- Set up authentication with Google
- Make requests to the YouTube API using the Google API client library
- Use Streamlit to build a web app for browsing YouTube Shorts
I hope this article has been helpful in getting started with building your own Streamlit apps that interact with APIs. Good luck with your future projects!
Subscribe and clap to get new post notifications daily. As I’ll be daily uploading new scripts that i create with ChatGPT. Peace