10 September 2011

Working with YouTube API from Python - A Primer

Grabbing data from YouTube with Python is really simple and you can build a ton of apps using this information. It's nothing more than making an HTTP GET request to the proper gdata URL. Then we just take the response in JSON format, decode it, and then can work with it like any other Python dictionary.
#!/usr/bin/env python
import requests
import json

resp = requests.get("http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2&alt=jsonc")
if(resp.status_code == 200):
	data = json.loads(resp.content)
	for item in data['data']['items']:
		print "Video Title: %s" % (item['title'])
		print "Video Category: %s" % (item['category'])
		print "Video ID: %s" % (item['id'])
		print "Video Rating: %f" % (item['rating'])
		print "Embed URL: %s" % (item['player']['default'])
	print "There was a problem retrieving the data"
The results look something like this:
Video Title: Minecraft - Dwarf Hole (Diggy Diggy Hole) Fan Song and Animation
Video Category: Shows
Video ID: fR7EAdPUqvQ
Video Rating: 4.862668
Embed URL: http://www.youtube.com/watch?v=fR7EAdPUqvQ&feature=youtube_gdata_player

Video Title: FAT KID FALLS
Video Category: Entertainment
Video ID: dCd8ojAdUbA
Video Rating: 4.671462
Embed URL: http://www.youtube.com/watch?v=dCd8ojAdUbA&feature=youtube_gdata_player

Video Title: Incredible Shade Illusion!
Video Category: Tech
Video ID: z9Sen1HTu5o
Video Rating: 4.793279
Embed URL: http://www.youtube.com/watch?v=z9Sen1HTu5o&feature=youtube_gdata_player

Video Title: David Guetta feat. Sia - Titanium
Video Category: Music
Video ID: Mb6mS6Yj_UA
Video Rating: 4.845408
Embed URL: http://www.youtube.com/watch?v=Mb6mS6Yj_UA&feature=youtube_gdata_player

Video Title: 50 Cal Machine Gun VS. 250 Watermelons
Video Category: Entertainment
Video ID: XyoAP10uKTk
Video Rating: 4.921269
Embed URL: http://www.youtube.com/watch?v=XyoAP10uKTk&feature=youtube_gdata_player

[ ... cut for space ... ]

No comments:

Post a Comment