From Freebase

Jump to: navigation, search


This library provides a python interface to the Freebase API available via HTTP web services. It also includes command-line utilities and APIs for creating, dumping, and reloading types and properties.

Install using pip or easy_install (e.g. sudo pip install freebase):

Freebase API and Python

This article contains content originally taken from the MQL Manual, which is no longer maintained. It may need cleanup to make sense as a standalone document. Please go ahead and help us do this!

NOTE: This page has been recently updated to refer to the current Python library, but a) that library still uses the old Freebase APIs, not the new Google APIs which are being developed and b) this page may still contain legacy references to which have been missed. That was an early incarnation of the code which became the freebase-python module.

The freebase-python module is a Python module for working with Freebase services. This module defines a metaweb.Session object that represents the host name of a Freebase server, and also encapsulates a set of options (such as the lang option to mqlread and the maxwidth option to /api/trans/image_thumb). Each Session object also maintains a "cookie jar" for storing any HTTP cookies returned by Freebase services, and uses those cookies in any subsequent requests made. (Cookies are used for authentication and caching, and are discussed in MQL Manual/mqlwrite.)

One feature of the first example is of particular note. The mqlreaditer() method of the freebase.HTTPMetawebSession class is a generator that returns the results of a MQL query one at a time, and uses the cursor envelope parameter to submit a MQL query as many times as necessary to retrieve all available results. You might use it in code like this:

import freebase                                 # Use the Freebase module
freebase = freebase.HTTPMetawebSession("") # Create a Session object
albums_by_bob = [{'type':'/music/album',       # This is our MQL query
                  'artist':'Bob Dylan',
                  'name':None }]
for album in freebase.mqlreaditer(albums_by_bob):  # Loop through query results
    print album["name"]                        # Print album names

The second example is a Python version of the band examples on the MQLRead pages: it lists albums by a specified band or searches for bands whose name is like a specified string. It demonstrates the freebase-python module in more detail, showing how to use the read() method to invoke mqlread, the search() method to invoke the search service, and the blurb() method to invoke the /api/trans/blurb service.

<example id="">

Using the freebase-python module to read, search and download

import sys            # Command-line arguments, etc.
import freebase        # Freebase services

band = sys.argv[1]                       # The band the user is asking about
query = { 'type': '/music/artist',       # Our MQL query in Python.
          'name': band,                  # Place the band in the query.
          'album': [{ 'name': None,
                      'release_date': None,
                      'sort': 'release_date' }]}

freebase = freebase.HTTPMetawebSession("") # Create a session object
result = freebase.mqlread(query)                  # Submit query, get results
if result:                                     # If we got a result
    print("Albums by %s:" % result['name'])    # print the album names
    print("\n".join([album['name'] for album in result['album']]))
else:                                          # Otherwise: no result + "*",        # Start a search
                            type="/music/artist",  # Only for bands
                            limit=5)               # We only want 5
    if (len(matches) == 0):                    # If no search results
        print "Unknown band."                  # Give up.
    else:                                      # If we got some search results
        print "Did you mean one of these?:"
        for match in matches:                  # Loop through the matches
            print match['name']                # Print the name of the match
            article = match['article']         # Get associated article
            if article:                        # If there is an article
                text = freebase.blurb(article['id'],  # Download a blurb
                                           maxlength=100)  # 100 chars long
                print text                                # And print it

Personal tools