Skip to content

Commit 04091bb

Browse files
"Added sample: python/search.py"
1 parent d732957 commit 04091bb

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

python/search.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#!/usr/bin/python
2+
3+
from apiclient.discovery import build
4+
from apiclient.errors import HttpError
5+
from oauth2client.tools import argparser
6+
7+
8+
# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
9+
# tab of
10+
# https://cloud.google.com/console
11+
# Please ensure that you have enabled the YouTube Data API for your project.
12+
DEVELOPER_KEY = "REPLACE_ME"
13+
YOUTUBE_API_SERVICE_NAME = "youtube"
14+
YOUTUBE_API_VERSION = "v3"
15+
16+
def youtube_search(options):
17+
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
18+
developerKey=DEVELOPER_KEY)
19+
20+
# Call the search.list method to retrieve results matching the specified
21+
# query term.
22+
search_response = youtube.search().list(
23+
q=options.q,
24+
part="id,snippet",
25+
maxResults=options.max_results
26+
).execute()
27+
28+
videos = []
29+
channels = []
30+
playlists = []
31+
32+
# Add each result to the appropriate list, and then display the lists of
33+
# matching videos, channels, and playlists.
34+
for search_result in search_response.get("items", []):
35+
if search_result["id"]["kind"] == "youtube#video":
36+
videos.append("%s (%s)" % (search_result["snippet"]["title"],
37+
search_result["id"]["videoId"]))
38+
elif search_result["id"]["kind"] == "youtube#channel":
39+
channels.append("%s (%s)" % (search_result["snippet"]["title"],
40+
search_result["id"]["channelId"]))
41+
elif search_result["id"]["kind"] == "youtube#playlist":
42+
playlists.append("%s (%s)" % (search_result["snippet"]["title"],
43+
search_result["id"]["playlistId"]))
44+
45+
print "Videos:\n", "\n".join(videos), "\n"
46+
print "Channels:\n", "\n".join(channels), "\n"
47+
print "Playlists:\n", "\n".join(playlists), "\n"
48+
49+
50+
if __name__ == "__main__":
51+
argparser.add_argument("--q", help="Search term", default="Google")
52+
argparser.add_argument("--max-results", help="Max results", default=25)
53+
args = argparser.parse_args()
54+
55+
try:
56+
youtube_search(args)
57+
except HttpError, e:
58+
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

0 commit comments

Comments
 (0)