Created
November 19, 2019 22:51
-
-
Save grant/eb98c7ba18c2f696eeb7b9da4d50b686 to your computer and use it in GitHub Desktop.
YouTube API on Cloud Run
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import argparse | |
from dotenv import load_dotenv | |
from flask import Flask, request | |
from googleapiclient.discovery import build | |
from googleapiclient.errors import HttpError | |
# Setup YouTube API | |
KEY = os.environ.get('KEY') | |
YOUTUBE_API_SERVICE_NAME = 'youtube' | |
YOUTUBE_API_VERSION = 'v3' | |
load_dotenv() | |
app = Flask(__name__) | |
@app.route('/') | |
def yt(): | |
if not KEY: | |
return '"KEY" env var is required' | |
youtube = build('youtube', 'v3', developerKey=KEY) | |
# Get YouTube API results | |
search_response = youtube.search().list( | |
q=request.args.get('q') or 'cats', | |
type='video', | |
part='id,snippet', | |
maxResults=10 | |
).execute() | |
items = search_response['items'] | |
if not items: | |
return 'Error: No YouTube results' | |
# Sent an HTML page with the top ten videos | |
def video_filter(api_video): | |
title = api_video['snippet']['title'] | |
videoid = api_video['id']['videoId'] | |
url = f'https://youtu.be/{videoid}' | |
return { | |
'title': title, | |
'url': url, | |
} | |
videos = list(map(video_filter, items)) | |
return { | |
'results': videos | |
} | |
if __name__ == "__main__": | |
app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment