YouTube API + Cloud Run
YouTube provides a free, easy, powerful API for querying and interacting with YouTube programmatically. In this article, we’ll talk about how to build a serverless application that returns random cat videos 🐱 using Cloud Run and the YouTube API in Python.
We’ll build our web application in 3 steps:
- Enable the YouTube API and create an API key.
- Write a Flask application in Python 3.
- Deploy the service to Cloud Run.
Set up the YouTube API
YouTube provides a variety of APIs for tasks such as querying videos, viewing video analytics, and live streaming.
The YouTube Data API (v3) allows us to easily query YouTube’s database of videos like is normally done in the search bar. An API key can be used for authentication.
Enable the YouTube Data API v3
Enable to the YouTube Data API (v3):
- Go to console.cloud.google.com/flows/enableapi?apiid=youtube.googleapis.com.
- Select your project and press
Continue
.
Download an API key
- Go to console.cloud.google.com/apis/credentials.
- Click
Create Credentials
, thenAPI key
. - Copy this key. You will need it later.
Install Python Dependencies
Make sure to use a virtual environment venv
with source env/bin/activate
.
For this demo, we’ll create a simple Python web server. Install Flask, the Google API client, and Google Auth helper with pip
:
pip install --upgrade flask google-api-python-client google-auth-httplib2
Write a Python Web Server Program
Create a Flask application that makes requests to the YouTube Data API (v3):
Run the Flask App Locally
We’ll test our web server locally with the Flask CLI:
export FLASK_APP=app.py
export KEY=AIzaSyCA-fe_wGJpUthisQgisl25fakeXqUNzk # Your API key
flask run
Replace the value of
KEY
with the API key you created from earlier.
Load the URL printed out in the terminal such as http://127.0.0.1:5000/
.
You can use the query parameter q
to search for different videos other than the default query cats
.
On the left is an example response from our API
Note: I use this extension for pretty JSON with clickable links.
Deploy the service to Cloud Run
To deploy to Google Cloud Run, we need to ensure our environment locally is the same as with Cloud Run. To do this, let’s create a .env
file to store our API key:
KEY=AIzaSyCA-fe_wGJpUthisQgisl25fakeXqUNzk # Your API key
We also need a Dockerfile
. The Dockerfile
states we need a container with Python 3.7, our application files, and our packages:
Run this shell script to build your container and deploy to Cloud Run:
Pawsome!
You just deployed a Flask application to Cloud Run that uses the YouTube API!
Next Steps
Thanks for reading! If you were interested in this blogpost, here are some related learning resources: