MQL Overview

  1. Overview
  2. MQL Read/Write Documentation
  3. Security considerations
  4. Using the Google client libraries
  5. MQL examples and recipes


The MQL Read and MQL Write APIs provides access to the Freebase database using the Metaweb query language (MQL).

Some examples of how you would use the MQL Read API include:

  • Get a collection of entities that share some common attributes or relations.
  • Get a specific set of facts about an entity.
  • Count the number of entities in Freebase that match certain criteria.
  • Query the individual links that make up the graph.

The following code samples, in several supported languages, show how execute a MQL read query for a list of countries and page through the results.


import json
import urllib

api_key = open(".freebase_api_key").read()
service_url = 'https://www.googleapis.com/freebase/v1/mqlread'
query = [{'id': None, 'name': None, 'type': '/astronomy/planet'}]
params = {
	'query': json.dumps(query),
	'key': api_key
url = service_url + '?' + urllib.urlencode(params)
response = json.loads(urllib.urlopen(url).read())
for planet in response['result']:
  print planet['name']


require 'rubygems'
require 'cgi'
require 'httparty'
require 'json'
require 'addressable/uri'

API_KEY = open(".freebase_api_key").read()
query = [{'id' => nil, 'name' => nil, 'type' => '/astronomy/planet'}]
url = Addressable::URI.parse('https://www.googleapis.com/freebase/v1/mqlread')
url.query_values = {
	'query' => query.to_json,
	'key'=> API_KEY
response = HTTParty.get(url, :format => :json)
response['result'].each { |topic|
  puts topic['name']
This example uses the Httparty and Addressable libraries.


package com.freebase.samples;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.jayway.jsonpath.JsonPath;
import java.io.FileInputStream;
import java.util.Properties;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class MqlreadSample {
  public static Properties properties = new Properties();
  public static void main(String[] args) {
    try {
      properties.load(new FileInputStream("freebase.properties"));
      HttpTransport httpTransport = new NetHttpTransport();
      HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
      JSONParser parser = new JSONParser();
      String query = "[{\"id\":null,\"name\":null,\"type\":\"/astronomy/planet\"}]";
      GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread");
      url.put("query", query);
      url.put("key", properties.get("API_KEY"));
      HttpRequest request = requestFactory.buildGetRequest(url);
      HttpResponse httpResponse = request.execute();
      JSONObject response = (JSONObject)parser.parse(httpResponse.parseAsString());
      JSONArray results = (JSONArray)response.get("result");
      for (Object result : results) {
    } catch (Exception ex) {


<!DOCTYPE html>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <body><aside class="warning"><strong>Warning: </strong>The Freebase API will be retired on June 30, 2015. <a href="https://plus.sandbox.google.com/109936836907132434202/posts/bu3z2wVqcQc">Read more</a>.</aside>
      var query = [{'id': null, 'name': null, 'type': '/astronomy/planet'}];
      var service_url = 'https://www.googleapis.com/freebase/v1/mqlread';
      $.getJSON(service_url + '?callback=?', {query:JSON.stringify(query)}, function(response) {
        $.each(response.result, function(i,planet){
This example uses the jQuery library.


<!DOCTYPE html>
	$query = array(array('id' => NULL, 'name' => NULL, 'type' => '/astronomy/planet'));
	$service_url = 'https://www.googleapis.com/freebase/v1/mqlread';
	$params = array(
		'query' => json_encode($query),
		'key' => $freebase_api_key
	$url = $service_url . '?' . http_build_query($params);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$response = json_decode(curl_exec($ch), true);
	foreach ($response['result'] as $topic) {
		echo $topic['name'] . '<br/>';

Also see the Client Libraries page to see if your favorite language is supported.

Using MQL Write

MQL Write supports legacy developer applications that write to Freebase.

MQL Read/Write API Documentation

Also see the following docs:

  • See the MQL Read and MQL Write Reference documentation for details on how to use these services.
  • See the MQL Manual for details on using the Metaweb Query Language

Security considerations

The MQL Read API works with user generated content stored in the Freebase graph. This means that you cannot directly use the content on a web page without safely escaping it first.

See Getting Started: Security for more information.

Querying for info as of a certain time

This example uses the as_of_time parameter to return a list of Madona's children as of January 2009.


Try it.

This query returns:

  "result": {
    "type": "/people/person",
    "id": "/en/madonna",
    "children": [
      "Lourdes Maria Ciccone Leon",
      "Rocco Ritchie",
      "David Banda Mwale Ciccone Ritchie"

Querying with 'cursor' and paging through results.

This example uses cursor to return albums by Bob Dylan 3 at a time per page. Using cursor allows you to page through the results.

You can specify different values for limit to specify a different amount of results per page. If you do not specify a limit, MQL will default to 100 results per page.


Try it.

This query returns 3 entries and a value for cursor (in bold below):

 "cursor": "eNp9js1qhEAQhB8mFyUM23-O3U1Y8h6Dh0EdIgQVTZaQp4-yYXNLXerQVfV1_7nty-Yl8-Bpce7S7GLIkTm2XZ4Hf4Ig2sZIZuLkad2_z9hyc-iqMn2Ng98tTHt2VhIN0raAjRn6-0uobtPqZorCRo-txrdnI6CsPQgARMGi8CvEPOowhms8VtBI6_Q2zR8Hsa6rE3P8ZEjIon8I1EaYhB8n-g9xVx-uZw0a5bpO67YciAsik4FdXptSABmYBZUw0g-ylUxj",
 "result": [
     "type": "/music/album",
     "name": "Blood on the Tracks",
     "artist": {
       "id": "/en/bob_dylan"
     "type": "/music/album",
     "name": "\"Love and Theft\"",
     "artist": {
       "id": "/en/bob_dylan"
     "type": "/music/album",
     "name": "Highway 61 Revisited",
     "artist": {
       "id": "/en/bob_dylan"

In order to request the next page of entries, follow it with an identical request but replace value for cursor with the value returned in the previous response.


Try it.

This returns the next page of 3 items with a new value for cursor.

"cursor": "eNp9zs9KxEAMBvCH8dIiw-bfzCRBFt9j6GFou1iQtrS6iE9vlxUFD36XHMKXX_r3bV82r1oHL4unrswuhpyYU-7qPPgDK4kGyRkwmqGTl3X_dO7KcnXomsv0MQ5-H2Haq_8tvD6F5jqtbqYobBREc0pkFn17NAKq2oMAQBK8KHwHsY46jOGcjitopG15mea3Q2zb5sZAOB4lZNFfAjUKk_DPiv4j7unD-VaDqNy2Zd2WgzgRZ7XIZV1du9NzjpqQgVkyACX5AphVTvE=",
"result": [
  "type": "/music/album",
  "name": "Bringing It All Back Home",
  "artist": {
   "id": "/en/bob_dylan"
  "type": "/music/album",
  "name": "The Freewheelin' Bob Dylan",
  "artist": {
   "id": "/en/bob_dylan"
  "type": "/music/album",
  "name": "Bob Dylan",
  "artist": {
   "id": "/en/bob_dylan"

Repeat this until you've reached the end of available results.

Freebase returns FALSE for the value of cursor when you have reached the end.

Looping through cursor results

This sample shows an example of how to loop through the results from a query using cursor to get the ID and Name of every film in Freebase.

from apiclient import discovery
from apiclient import model
import json


model.JsonModel.alt_param = ""
freebase = discovery.build('freebase', 'v1', developerKey=DEVELOPER_KEY)
query = [{'id': None, 'name': None, 'type': '/film/film'}]

def do_query(cursor=""):

    response = json.loads(freebase.mqlread(query=json.dumps(query), cursor=cursor).execute())
    for item in response['result']:
        print item['name']

    return response.get("cursor")

cursor = do_query()
    cursor = do_query(cursor)

Create new topic in sandbox with MQL Write

This Java example uses the MQL Write API to create a new topic in the Sandbox developer environment.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.Arrays;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;

public class FreebaseMQLWriteSample, {

    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    private static final JsonFactory JSON_FACTORY = new JacksonFactory();

    // User settings
    private static final String CLIENT_ID = "YOUR-CLIENT-ID";
    private static final String CLIENT_SECRET = "YOUR-CLIENT-SECRET";
    private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";

    private static final String SCOPE = "https://www.googleapis.com/auth/freebase";
    private static final String MQLWRITE = "https://www.googleapis.com/freebase/v1sandbox/mqlwrite";

    public static void main(String[] args) {
        new FreebaseMQLWriteSample();

    public String requestAuthCode() throws IOException {
        String url = new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, CALLBACK_URL, Arrays.asList(SCOPE)).setState("/profile").build();
        System.out.println("Go to this url, login, and past the code: " + url);

        InputStreamReader converter = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(converter);
        return in.readLine();
    public GoogleTokenResponse requestAuthToken(String authCode) throws IOException {
        return new GoogleAuthorizationCodeTokenRequest(HTTP_TRANSPORT, JSON_FACTORY,
                CLIENT_ID, CLIENT_SECRET, authCode, CALLBACK_URL).execute();
    public FreebaseTest() {
        try {
            String auth = requestAuthCode();
            GoogleTokenResponse token = requestAuthToken(auth);

            GoogleCredential cred = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                    .setClientSecrets(CLIENT_ID, CLIENT_SECRET)


            String query = "{\"create\":\"unconditional\",\"id\":null,\"name\":\"Nowhere\",\"type\":\"/location/location\"}";
            String url = MQLWRITE + "?oauth_token=" + cred.getAccessToken() + "&query=" + URLEncoder.encode(query, "UTF-8");

            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            HttpResponse response = client.execute(get);

            System.out.println("Attempting: " + get.getURI().toString());
            System.out.println("Response: " + EntityUtils.toString(response.getEntity()));

        } catch (IOException e) {

Send feedback about...

Freebase API (Deprecated)
Freebase API (Deprecated)