Search with Freebase Topics

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.


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.


  • 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 Google Developers Console, select APIs & auth in the sidebar. Then 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:


 "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": [

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.


  "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.


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.

  • --max-results – The number of YouTube resources that you want to retrieve after selecting a Freebase topic.

  • --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.


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.


from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser

import json
import urllib

# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
#   https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
FREEBASE_SEARCH_URL = "https://www.googleapis.com/freebase/v1/search?%s"

def get_topic_id(options):
  # Retrieve a list of Freebase topics associated with the provided query term.
  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.")

  # Display the list of matching Freebase topics.
  mids = []
  index = 1
  print "The following topics were found:"
  for result in freebase_response["result"]:
    print "  %2d. %s (%s)" % (index, result.get("name", "Unknown"),
      result.get("notable", {}).get("name", "Unknown"))
    index += 1

  # Display a prompt for the user to select a topic and return the topic ID
  # of the selected topic.
  mid = None
  while mid is None:
    index = raw_input("Enter a topic number to find related YouTube %ss: " %
      mid = mids[int(index) - 1]
    except ValueError:
  return mid

def youtube_search(mid, options):

  # Call the search.list method to retrieve results associated with the
  # specified Freebase topic.
  search_response = youtube.search().list(

  # Print the title and ID of each matching resource.
  for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
      print "%s (%s)" % (search_result["snippet"]["title"],
    elif search_result["id"]["kind"] == "youtube#channel":
      print "%s (%s)" % (search_result["snippet"]["title"],
    elif search_result["id"]["kind"] == "youtube#playlist":
      print "%s (%s)" % (search_result["snippet"]["title"],

if __name__ == "__main__":
  argparser.add_argument("--query", help="Freebase search term", default="Google")
  argparser.add_argument("--max-results", help="Max YouTube results",
    help="YouTube result type: video, playlist, or channel", default="channel")
  args = argparser.parse_args()

  mid = get_topic_id(args)
    youtube_search(mid, args)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

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: