(Quick Reference)

4 Facebook Graph Client - Reference Documentation

Authors: Benoit Hediard

Version: 2.3.0

4 Facebook Graph Client

WARNING: Since V2.1.0, FacebookGraphClient constructor has changed with a new apiVersion parameter (default to V2.1).
// From
FacebookGraphClient(String accessToken = '', Integer timeout = DEFAULT_READ_TIMEOUT_IN_MS, String proxyHost = null, Integer proxyPort = null) {
// To
FacebookGraphClient(String accessToken = '', String apiVersion = DEFAULT_API_VERSION, Integer timeout = DEFAULT_READ_TIMEOUT_IN_MS, String proxyHost = null, Integer proxyPort = null) {

To perform Facebook Graph API call, use the FacebookGraphClient without access token for public data or with an access token for private data. FacebookGraphClient is a thin groovy wrapper around the rock solid RestFB java library . It will return JSON-based graph objects.

To play with the API, you might use the grails console from your project root and get user token or app token from Facebook Access Token Tool .

grails console

Initialization

import grails.plugin.facebooksdk.FacebookGraphClient

// For public data def facebookClient = new FacebookGraphClient()

// For private data (access token required) def userAccessToken = facebookAppService.getUserAccessToken() // Or any app/user token def facebookClient = new FacebookGraphClient(userAccessToken)

// With specific api version def facebookClient = new FacebookGraphClient(userAccessToken, 'v1.0')

// With specific timeout (default to 180s) def facebookClient = new FacebookGraphClient(userAccessToken, FacebookGraphClient.DEFAULT_API_VERSION, 90000)

// With proxy support def facebookClient = new FacebookGraphClient(userAccessToken, FacebookGraphClient.DEFAULT_API_VERSION, FacebookGraphClient.DEFAULT_READ_TIMEOUT_IN_MS, '192.168.0.10', 8080)

Fetching Single Objects

def user = facebookClient.fetchObject("me") // Requires a user access token
def page = facebookClient.fetchObject("cocacola")
println "User name: " + user.name
println "Page likes: " + page.likes

Fetching Multiple Objects in One Call

def fetchObjectsResults = facebookClient.fetchObjects(["me", "cocacola"])
println "User name: " + fetchObjectsResults["me"].name
println "Page likes: " + fetchObjectsResults["cocacola"].likes

Fetching Connections

Make sure that you asked for the corresponding user permissions, e.g. user_status for the feed, user_photos for the photos, etc.

def myFriends = facebookClient.fetchConnection("me/friends")
def myFeed = facebookClient.fetchConnection("me/feed")
println "Count of my friends: " + myFriends.size()
println "First item in my feed: " + myFeed[0]

Searching

// Searching is just a special case of fetching Connections -
// all you have to do is pass along a few extra parameters.
def publicSearch = facebookClient.fetchConnection("search", [q:"watermelon", type:"post"])
println "Public search: " + publicSearch[0].message
// Targeted search
def targetedSearch = facebookClient.fetchConnection("me/home", [q:"Mark", type:"user"])
println "Posts on my wall by friends named Mark: " + targetedSearch.size()

Fetching Insights

// Fetching Insights data is as simple as fetching a Connection
def insights = facebookClient.fetchConnection("PAGE_ID/insights")
for (insight in insights) println insight.name

Executing FQL Queries

String query = "SELECT uid, name FROM user WHERE uid=220439 or uid=7901103"
def users = facebookClient.executeQuery(query)
println "Users: " + users

Executing Multiple FQL Queries in One Call

Map queries = [users:"SELECT uid, name FROM user WHERE uid=220439 OR uid=7901103", likers:"SELECT user_id FROM like WHERE object_id=122788341354"]
multiqueryResults = facebookClient.executeMultiquery(queries)
println "Users: " + multiqueryResults.users
println "People who liked: " + multiqueryResults.likers

Metadata/Introspection

// You can specify metadata=1 for many calls, not just this one.
// See the Facebook Graph API documentation for more details.
def userWithMetadata = facebookClient.fetchObject("me", [metadata:1])
println "User connections  " + userWithMetadata.metadata.connections

Passing Parameters

// You can pass along any parameters you'd like to the Facebook endpoint.
Date oneWeekAgo = new Date() - 7
def filteredFeed = facebookClient.fetchConnection("me/feed", [limit:3, until:"yesterday", since:oneWeekAgo])
println "Filtered feed count: " + filteredFeed.size()

Selecting Specific Fields

def user = facebookClient.fetchObject("me", [fields:"id, name"])
println "User name: " + user.name

Publishing a Message and Event

// Publishing a simple message.
def publishMessageResponse = facebookClient.publish("me/feed", [message:"RestFB test"])
println "Published message ID: " + publishMessageResponse.id

// Publishing an event Date tomorrow = new Date() + 1 Date twoDaysFromNow = new Date() + 2 def publishEventResponse = facebookClient.publish("me/events", [name:"Party", start_time:tomorrow, end_time:twoDaysFromNow]) println "Published event ID: " + publishEventResponse.id

Publishing a Photo or a Video

// Publishing an image to a photo album is easy!
// Just specify the image you'd like to upload and RestFB will handle it from there.
def publishPhotoResponse = facebookClient.publish("me/photos", [message, "Test cat"], "/Users/ben/Downloads/cat.png")
println "Published photo ID: " + publishPhotoResponse.id
// Publish a submitted file
def publishPhotoResponse = facebookClient.publish("me/photos", [message, "Test upload"], multipartFile.originalFilename, multipartFile.inputStream)
// Publish an existing remote file by URL
def someUrl = "http://www.google.com/images/logo.gif"
def publishPhotoResponse = facebookClient.publish("me/photos", [message, "Test logo"], "logo.gif", new URL(someUrl).openStream())
println "Published photo ID: " + publishPhotoResponse.id
// Publishing a video works the same way.
facebookClient.publish("me/videos", [message, "Test cat"], "/Users/ben/Downloads/cat.mov")

Deleting

Boolean deleted = facebookClient.deleteObject("some object ID")
out.println("Deleted object? " + deleted)

Using the Batch Request API

List batchResponses = facebookClient.executeBatch(["me", "m83music/feed"]);
// Responses are ordered to match up with their corresponding requests.
println "Me object " + batchResponses[0]
println "M83 feed " + batchResponses[1]

Error Handling

All FacebookClient methods may throw com.restfb.exception.FacebookException, which is an unchecked exception as of RestFB 1.6.

These are the FacebookException subclasses that you may catch:

  • FacebookJsonMappingException
  • FacebookNetworkException
  • FacebookGraphException
  • FacebookOAuthException
  • FacebookQueryParseException
  • FacebookResponseStatusException

For more info, check RestFB java library documentation.