Read API Code Snippets
From Freebase
This page shows you how to query the Freebase Read Service using your favorite programming language. You'll need facilities to encode and decode JSON as well as fetch an HTTP URL. For a more detailed description of how to use the Read Service please take a look at the MQL Manual
Each of the code snippets below will query Freebase for a list of planets and display their names using the following query:
[{
"id": null,
"name": null,
"type": "/astronomy/planet"
}]
This corresponds to the following HTTP GET request (click the link to see the response format):
http://api.freebase.com/api/service/mqlread?query={"query":[{"id":null,"name":null,"type":"/astronomy/planet"}]}
Contents |
ActionScript
This sample code uses the ActionScript 3 Core Library to parse the JSON data.
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.*;
import com.adobe.serialization.json.JSON;
var query = [{'id': null, 'name': null, 'type': '/astronomy/planet'}];
var query_envelope = {'query': query};
var service_url = 'http://api.freebase.com/api/service/mqlread';
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest();
request.url = service_url + "?&query=" + encodeURIComponent(JSON.encode(query_envelope));
loader.load(request) ;
loader.addEventListener(Event.COMPLETE, function(event:Event):void {
var results:Array = JSON.decode(loader.data).result;
for each(var planet:Object in results) {
trace(planet.name) ;
}
});
Also see: Flash libraries
C#
TODO
How to make calls to Freebase API from .NET - code sample shows how to create freebase query from .NET object and parse API response. This sample uses only standard .NET 3.5 or 4.0 libraries.
Also see: .Net libraries
Java
The following snippet uses the HttpClient and json-simple libraries.
String query = "[{\"id\":null,\"name\":null,\"type\":\"/astronomy/planet\"}]";
String query_envelope = "{\"query\":" + query + "}";
String service_url = "http://api.freebase.com/api/service/mqlread";
String url = service_url + "?query=" + URLEncoder.encode(query_envelope, "UTF-8");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
JSONParser parser = new JSONParser();
JSONObject json_data = (JSONObject)parser.parse(EntityUtils.toString(response.getEntity()));
JSONArray results = (JSONArray)json_data.get("result");
for (Object planet : results) {
System.out.println(((JSONObject)planet).get("name"));
}
Also see: Java libraries
Javascript
This snippet makes an Ajax call to the Freebase API useing jQuery and the json2 library.
<!DOCTYPE html>
<title>MqlRead in JavaScript</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!-- for older browsers: <script src="json2.js"></script> -->
<script>
var query = [{'id': null, 'name': null, 'type': '/astronomy/planet'}];
var query_envelope = {'query' : query};
var service_url = 'http://api.freebase.com/api/service/mqlread';
$.getJSON(service_url + '?callback=?', {query:JSON.stringify(query_envelope)}, function(response) {
$.each(response.result, function(i,planet){
$('<div>',{text:planet.name})
.appendTo(document.body);
});
});
</script>
Also see: Javascript libraries
Objective-C
TODO
Also see: Objective-C libraries
Perl
use URI::Escape;
use LWP::Simple;
use JSON;
$query = [{id => undef, name => undef, type => '/astronomy/planet'}];
$query_envelope = {query => $query};
$service_url = 'http://api.freebase.com/api/service/mqlread';
$url = $service_url . "?query=" . uri_escape(encode_json($query_envelope));
$results = decode_json(get($url))->{result};
foreach $planet (@$results) {
print $planet->{name} . "\n";
}
Also see: Perl libraries
PHP
$query = array(array('id' => NULL, 'name' => NULL, 'type' => '/astronomy/planet'));
$query_envelope = array('query' => $query);
$service_url = 'http://api.freebase.com/api/service/mqlread';
$url = $service_url . '?query=' . urlencode(json_encode($query_envelope));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
foreach ($response['result'] as $planet) {
echo $planet['name'] . '<br/>';
}
Also see: PHP libraries
Python
import sys
import json
import urllib
query = [{'id': None, 'name': None, 'type': '/astronomy/planet'}]
query_envelope = {'query': query}
service_url = 'http://api.freebase.com/api/service/mqlread'
url = service_url + '?query=' + json.dumps(query_envelope);
response = json.loads(urllib.urlopen(url).read())
for planet in response['result']:
print planet['name']
Also see: Python libraries
Ruby
One way to make a Freebase API call in Ruby is to use the HTTParty libarary.
require 'cgi'
require 'httparty'
require 'json'
query = [{'id' => nil, 'name' => nil, 'type' => '/astronomy/planet'}]
query_envelope = {'query' => query }
service_url = 'http://api.freebase.com/api/service/mqlread'
url = service_url + '?query=' + CGI::escape(query_envelope.to_json)
response = HTTParty.get(url, :format => :json)
response['result'].each { |planet|
puts planet['name']
}
Also see: Ruby libraries