YouTube

YouTube Data API - Searching with Freebase Topics

experimental feature
The YouTube Data API (v3) is an experimental API version, which means it is still in development. We'll be adding many more features to the API while it is still an experimental version. Until the experimental label is removed, however, the Deprecation Policy for YouTube APIs won't apply to this version as discussed in the API Terms of Service.

This guide explains how you can use Freebase topics in your YouTube Data API implementation to help users find YouTube content related to a certain topic. It describes the ways that Freebase topics are used in API resources and search requests. It also provides sample code for an application that searches for a Freebase topic and then retrieves related YouTube resources.

Freebase is an open, Creative Commons licensed repository that contains tens of millions of topics. Each Freebase topic represents a single concept or real-world thing. Topics identify people, buildings and landmarks, films, hobbies, medical concepts, and more.

Contents

This guide contains the following sections:

  • The Requirements section identifies prerequisites for running the sample code in this guide and for integrating your application with Freebase.

  • The Freebase topics in the API section explains the ways that Freebase topics are used in YouTube Data API resources and search requests.

  • The Sample code section describes and provides sample code that retrieves Freebase topics associated with a particular query term. The code also retrieves YouTube resources associated with a selected Freebase topic.

  • The Additional resources section identifies other documentation that will help you better understand this guide and how to integrate Freebase topics and the YouTube Data API in your own application.

Requirements

  • Register your application with Google. Note that since the sample code in this guide doesn't require you to authorize access to user data, you do not need to complete the registration steps for creating an OAuth 2.0 client ID to run these code samples.

  • In the API console, go to the Services pane and set the status of the Freebase API and the YouTube Data API to ON.

  • Language-specific requirements:

Freebase topics in the API

The sections below explain how Freebase topics are used in YouTube Data API resources and search requests.

Freebase topics in API resources

The API's channel and video resources all contain a topicDetails object. For any given resource, that object contains a list of Freebase topic IDs, each of which identifies a topic associated with the resource.

To retrieve the topics for the resources returned in a channels.list or videos.list request, the request's part parameter value must include the topicDetails object. An example is shown below:

Request:
https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&part=snippet,topicDetails

Response:
{
 "kind": "youtube#videoListResponse",
 "etag": "\"r3ahjFekUqNiL0By9B5wQ2uTZHM/i4Bt9XfY8YZ1ctSlg8BWcLD8HFQ\"",
 "items": [
  {
   "id": "7lCDEYXw3mM",
   "kind": "youtube#video",
   "etag": "\"r3ahjFekUqNiL0By9B5wQ2uTZHM/hYUGsnkhqATV4OXNG43HIObqlyw\"",
   "snippet": {
    "title": "Google I/O 101: Q&A On Using Google APIs",
    [ some properties have been omitted here ],
    "categoryId": "28"
   },
   "topicDetails": {
    "topicIds": [
     "/m/045c7b",
     "/m/0z5n",
     "/m/04136kj"
    ]
   }
  }
 ]
}

Your application can then use the Freebase Topic API to retrieve the name and additional metadata for each topic associated with the resource. The Freebase Query Editor demonstrates how to make this call.

Freebase topics in API search requests

Your application can use the Freebase Search Service to find Freebase topics associated with a particular keyword. For example, the request below retrieves Freebase topics associated with the query Python. The mid property in each result identifies the associated topic's unique Freebase topic ID.

Request:
https://www.googleapis.com/freebase/v1/search?query=Python&indent=true

Response:
{
  "status": "200 OK",
  "result": [
    {
      "mid": "/m/05z1_",
      "id": "/wikipedia/fr/Python_$0028langage$0029",
      "name": "Python",
      "notable": {
        "name": "Programming Language",
        "id": "/computer/programming_language"
      },
      "lang": "en",
      "score": 146.811295
    },
    {
      "mid": "/m/06ggzm",
      "id": "/en/indian_python",
      "name": "Indian Python",
      "notable": {
        "name": "Organism Classification",
        "id": "/biology/organism_classification"
      },
      "lang": "en",
      "score": 48.635296
    },
    ...
  ]
}

The API's search.list method then lets you search for resources associated with a particular Freebase topic by using the topicId request parameter to identify that topic. Note that you also need to specify an empty q parameter (q=) in your request since that parameter is required when searching by topic.

Sample code

This section provides sample code for an application that performs the following functions:

  1. It retrieves a list of Freebase topics that match a specified search query.

  2. It displays the topics and prompts the user to select a topic.

  3. It retrieves and displays a list of YouTube resources that are associated with the selected topic. Resources could be channels, playlists, videos, or any combination of those types.

Python

Note: This example uses the Python client library.

Sample request

The sample request below retrieves Freebase topics associated with the keyword Python and then retrieves 10 YouTube channels associated with a selected topic.

python topics.py --query="Python" --max-results=10 --type="channel"

Calling the script

The list below defines the script's command-line arguments:

  • --query – The search term for which you want to find matching Freebase topics.

    Example:
    --query="Python"
  • --max-results – The number of YouTube resources that you want to retrieve after selecting a Freebase topic.

    Example:
    --max-results=10
  • --type – The types of YouTube resources to retrieve after selecting a Freebase topic. The value is a comma-separated string containing one or more of the following values: channel, playlist, and video. The default value in this example is channel.

    Example:
    --type="video,channel"

Sample code

The complete working sample for the topics.py script is listed below. This code makes a direct REST call to the Freebase API and uses the client library to make the YouTube API call.

#!/usr/bin/python

from apiclient.discovery import build
from optparse import OptionParser

import json
import urllib


# Set DEVELOPER_KEY to the "API key" value from the "Access" tab of the
# Google APIs Console http://code.google.com/apis/console#access
# Please ensure that you have enabled the YouTube Data API and Freebase API
# for your project.
DEVELOPER_KEY = "REPLACE_ME"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
FREEBASE_SEARCH_URL = "https://www.googleapis.com/freebase/v1/search?%s"

def get_topic_id(options):
  freebase_params = dict(query=options.query, key=DEVELOPER_KEY)
  freebase_url = FREEBASE_SEARCH_URL % urllib.urlencode(freebase_params)
  freebase_response = json.loads(urllib.urlopen(freebase_url).read())

  if len(freebase_response["result"]) == 0:
    exit("No matching terms were found in Freebase.")

  mids = []
  index = 1
  print "The following topics were found:"
  for result in freebase_response["result"]:
    mids.append(result["mid"])
    print "  %2d. %s (%s)" % (index, result.get("name", "Unknown"),
      result.get("notable", {}).get("name", "Unknown"))
    index += 1

  mid = None
  while mid is None:
    index = raw_input("Enter a topic number to find related YouTube %ss: " %
      options.type)
    try:
      mid = mids[int(index) - 1]
    except ValueError:
      pass
  return mid


def youtube_search(mid, options):
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
  developerKey=DEVELOPER_KEY)

  search_response = youtube.search().list(
    # The q= parameter is currently required, but in the future just a topicId
    # will be sufficient.
    q=options.query,
    topicId=mid,
    type=options.type,
    part="id,snippet",
    maxResults=options.maxResults
  ).execute()

  for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
      print "%s (%s)" % (search_result["snippet"]["title"],
        search_result["id"]["videoId"])
    elif search_result["id"]["kind"] == "youtube#channel":
      print "%s (%s)" % (search_result["snippet"]["title"],
        search_result["id"]["channelId"])
    elif search_result["id"]["kind"] == "youtube#playlist":
      print "%s (%s)" % (search_result["snippet"]["title"],
        search_result["id"]["playlistId"])


if __name__ == "__main__":
  parser = OptionParser()
  parser.add_option("--query", dest="query", help="Freebase search term",
    default="Google")
  parser.add_option("--max-results", dest="maxResults",
    help="Max YouTube results", default=25)
  parser.add_option("--type", dest="type",
    help="YouTube result type: video, playlist, or channel", default="channel")
  (options, args) = parser.parse_args()

  mid = get_topic_id(options)
  youtube_search(mid, options)

Additional resources

  • The Freebase API documentation explains a collection of APIs that provide read and write access to Freebase data.

  • The reference documentation explains the fields in a YouTube search result.

  • This video features Shawn Simister from the Freebase team giving an overview of the Freebase Topics API and how it integrates with the YouTube Data API: