Module: Koala::Facebook::GraphAPIMethods

Included in:
API
Defined in:
lib/koala/api/graph_api.rb

Overview

Methods used to interact with the Facebook Graph API.

See github.com/arsduo/koala/wiki/Graph-API for a general introduction to Koala and the Graph API.

The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos, etc.) and the connections between them (e.g., friends, photo tags, event RSVPs, etc.). Koala provides access to those objects types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user’s friends:

You can see a list of all of the objects and connections supported by the API at developers.facebook.com/docs/reference/api/.

You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. If you’re using the JavaScript SDK, you can use the OAuth#get_user_from_cookie method to get the OAuth access token for the active user from the cookie provided by Facebook. See the Koala and Facebook documentation for more information.

Examples:

graph = Koala::Facebook::API.new(access_token)
user = graph.get_object("me")
friends = graph.get_connections(user["id"], "friends")

Instance Method Summary collapse

Instance Method Details

#batch(http_options = {}, &block) ⇒ Object

Execute a set of Graph API calls as a batch. See batch request documentation for more information and examples.

Examples:

results = @api.batch do |batch_api|
  batch_api.get_object('me')
  batch_api.get_object(KoalaTest.user1)
end
# => [{'id' => my_id, ...}, {'id' => koppel_id, ...}]

# You can also provide blocks to your operations to process the
# results, which is often useful if you're constructing batch
# requests in various locations and want to keep the code
# together in logical places.
# See readme.md and the wiki for more examples.
@api.batch do |batch_api|
  batch_api.get_object('me') {|data| data["id"] }
  batch_api.get_object(KoalaTest.user1) {|data| data["name"] }
end
# => [my_id, "Alex Koppel"]

Parameters:

  • http_options (defaults to: {})

    HTTP options for the entire request.

Returns:

  • an array of results from your batch calls (as if you’d made them individually), arranged in the same order they’re made.

Raises:

  • (Koala::Facebook::APIError)

    only if there is a problem with the overall batch request (e.g. connectivity failure, an operation with a missing dependency). Individual calls that error out will be represented as an unraised APIError in the appropriate spot in the results array.



440
441
442
443
444
445
446
447
448
# File 'lib/koala/api/graph_api.rb', line 440

def batch(http_options = {}, &block)
  batch_client = GraphBatchAPI.new(access_token, self)
  if block
    yield batch_client
    batch_client.execute(http_options)
  else
    batch_client
  end
end

#delete_connections(id, connection_name, args = {}, options = {}, &block) ⇒ Object

Note:

to access connections like /user_id/CONNECTION/other_user_id, simply pass “CONNECTION/other_user_id” as the connection_name

Delete an object’s connection (for instance, unliking the object).

Parameters:

  • id

    the object ID (string or number)

  • connection_name

    what

  • options (defaults to: {})

    request-related options for Koala and Faraday. See github.com/arsduo/koala/wiki/HTTP-Services for additional options.

Returns:

  • true if successful, false (or an APIError) if not

Raises:



161
162
163
164
165
# File 'lib/koala/api/graph_api.rb', line 161

def delete_connections(id, connection_name, args = {}, options = {}, &block)
  # Deletes a given connection
  raise AuthenticationError.new(nil, nil, "Delete requires an access token") unless @access_token
  graph_call("#{id}/#{connection_name}", args, "delete", options, &block)
end

#delete_like(id, options = {}, &block) ⇒ Object

Unlike a given object. Convenience method equivalent to delete_connection(id, “likes”).

Parameters:

Returns:

  • true if successful, false (or an APIError) if not

Raises:



290
291
292
293
294
# File 'lib/koala/api/graph_api.rb', line 290

def delete_like(id, options = {}, &block)
  # Unlikes a given object for the logged-in user
  raise AuthenticationError.new(nil, nil, "Unliking requires an access token") unless @access_token
  graph_call("#{id}/likes", {}, "delete", options, &block)
end

#delete_object(id, options = {}, &block) ⇒ Object

Delete an object from the Graph if you have appropriate permissions.

Parameters:

Returns:

  • true if successful, false (or an APIError) if not

Raises:



95
96
97
98
99
# File 'lib/koala/api/graph_api.rb', line 95

def delete_object(id, options = {}, &block)
  # Deletes the object with the given ID from the graph.
  raise AuthenticationError.new(nil, nil, "Delete requires an access token") unless @access_token
  graph_call(id, {}, "delete", options, &block)
end

#fql_multiquery(queries = {}, args = {}, options = {}, &block) ⇒ Object

Make an FQL multiquery. This method simplifies the result returned from multiquery into a more logical format.

Examples:

@api.fql_multiquery({
  "query1" => "select post_id from stream where source_id = me()",
  "query2" => "select fromid from comment where post_id in (select post_id from #query1)"
})
# returns {"query1" => [obj1, obj2, ...], "query2" => [obj3, ...]}
# instead of [{"name":"query1", "fql_result_set":[]},{"name":"query2", "fql_result_set":[]}]

Parameters:

Returns:

  • a hash of FQL results keyed to the appropriate query



345
346
347
348
349
350
351
352
# File 'lib/koala/api/graph_api.rb', line 345

def fql_multiquery(queries = {}, args = {}, options = {}, &block)
  resolved_results = if results = get_object("fql", args.merge(:q => MultiJson.dump(queries)), options)
    # simplify the multiquery result format
    results.inject({}) {|outcome, data| outcome[data["name"]] = data["fql_result_set"]; outcome}
  end

  block ? block.call(resolved_results) : resolved_results
end

#fql_query(query, args = {}, options = {}, &block) ⇒ Object

Make an FQL query. Convenience method equivalent to get_object(“fql”, :q => query).

Parameters:

Returns:

  • the result of the FQL query.



324
325
326
# File 'lib/koala/api/graph_api.rb', line 324

def fql_query(query, args = {}, options = {}, &block)
  get_object("fql", args.merge(:q => query), options, &block)
end

#get_comments_for_urls(urls = [], args = {}, options = {}, &block) ⇒ Object

Fetches the comments from fb:comments widgets for a given set of URLs (array or comma-separated string). See developers.facebook.com/blog/post/490.

Parameters:



380
381
382
383
384
# File 'lib/koala/api/graph_api.rb', line 380

def get_comments_for_urls(urls = [], args = {}, options = {}, &block)
  return [] if urls.empty?
  args.merge!(:ids => urls.respond_to?(:join) ? urls.join(",") : urls)
  get_object("comments", args, options, &block)
end

#get_connection(id, connection_name, args = {}, options = {}, &block) ⇒ Koala::Facebook::API::GraphCollection Also known as: get_connections

Note:

to access connections like /user_id/CONNECTION/other_user_id, simply pass “CONNECTION/other_user_id” as the connection_name

Fetch information about a given connection (e.g. type of activity – feed, events, photos, etc.) for a specific user. See Facebook’s documentation for a complete list of connections.

Parameters:

  • connection_name

    what

  • args (defaults to: {})

    any additional arguments

  • id

    the object ID (string or number)

  • options (defaults to: {})

    request-related options for Koala and Faraday. See github.com/arsduo/koala/wiki/HTTP-Services for additional options.

Returns:



115
116
117
118
# File 'lib/koala/api/graph_api.rb', line 115

def get_connection(id, connection_name, args = {}, options = {}, &block)
  # Fetches the connections for given object.
  graph_call("#{id}/#{connection_name}", args, "get", options, &block)
end

#get_object(id, args = {}, options = {}, &block) ⇒ Object

Get information about a Facebook object.

Examples:

get_object("me")  # => {"id" => ..., "name" => ...}
get_object("me") {|data| data['education']}  # => only education section of profile

Parameters:

  • id

    the object ID (string or number)

  • args (defaults to: {})

    any additional arguments (fields, metadata, etc. – see / Facebook’s documentation)

  • block

    for post-processing. It receives the result data; the return value of the method is the result of the block, if provided. (see Koala::Facebook::API#api)

  • options (defaults to: {})

    request-related options for Koala and Faraday. See github.com/arsduo/koala/wiki/HTTP-Services for additional options.

Returns:

  • a hash of object data

Raises:



56
57
58
59
# File 'lib/koala/api/graph_api.rb', line 56

def get_object(id, args = {}, options = {}, &block)
  # Fetches the given object from the graph.
  graph_call(id, args, "get", options, &block)
end

#get_objects(ids, args = {}, options = {}, &block) ⇒ Object

Get information about multiple Facebook objects in one call.

Parameters:

Returns:

  • an array of object data hashes

Raises:



71
72
73
74
75
76
# File 'lib/koala/api/graph_api.rb', line 71

def get_objects(ids, args = {}, options = {}, &block)
  # Fetches all of the given objects from the graph.
  # If any of the IDs are invalid, they'll raise an exception.
  return [] if ids.empty?
  graph_call("", args.merge("ids" => ids.respond_to?(:join) ? ids.join(",") : ids), "get", options, &block)
end

#get_page(params, &block) ⇒ Object

Note:

You’ll rarely need to use this method unless you’re using Sinatra or another non-Rails framework (see GraphCollection for more information).

Certain calls such as #get_connections return an array of results which you can page through forwards and backwards (to see more feed stories, search results, etc.). Those methods use get_page to request another set of results from Facebook.

Parameters:

Returns:

  • Koala::Facebook::GraphCollection the appropriate page of results (an empty array if there are none)



402
403
404
# File 'lib/koala/api/graph_api.rb', line 402

def get_page(params, &block)
  graph_call(*params, &block)
end

#get_page_access_token(id, args = {}, options = {}, &block) ⇒ Object

Get a page’s access token, allowing you to act as the page. Convenience method for @api.get_object(page_id, :fields => “access_token”).

Parameters:

Returns:

  • the page’s access token (discarding expiration and any other information)



363
364
365
366
367
368
369
# File 'lib/koala/api/graph_api.rb', line 363

def get_page_access_token(id, args = {}, options = {}, &block)
  access_token = get_object(id, args.merge(:fields => "access_token"), options) do |result|
    result ? result["access_token"] : nil
  end

  block ? block.call(access_token) : access_token
end

#get_picture(object, args = {}, options = {}, &block) ⇒ Object

Note:

to delete photos or videos, use delete_object(id)

Fetches a photo. (Facebook returns the src of the photo as a response header; this method parses that properly, unlike using get_connections(“photo”).)

Parameters:

  • options (defaults to: {})

    options for Facebook (see #get_object). To get a different size photo, pass :type => size (small, normal, large, square).

Returns:

  • the URL to the image



178
179
180
181
182
183
184
# File 'lib/koala/api/graph_api.rb', line 178

def get_picture(object, args = {}, options = {}, &block)
  # Gets a picture object, returning the URL (which Facebook sends as a header)
  resolved_result = graph_call("#{object}/picture", args, "get", options.merge(:http_component => :headers)) do |result|
    result["Location"]
  end
  block ? block.call(resolved_result) : resolved_result
end

#graph_call(path, args = {}, verb = "get", options = {}) { ... } ⇒ Object

Make a call directly to the Graph API. (See any of the other methods for example invocations.)

Parameters:

  • path

    the Graph API path to query (no leading / needed)

  • verb (defaults to: "get")

    the type of HTTP request to make (get, post, delete, etc.)

  • args (defaults to: {})

    any additional arguments (fields, metadata, etc. – see / Facebook’s documentation)

Yields:

  • response when making a batch API call, you can pass in a block that parses the results, allowing for cleaner code. The block’s return value is returned in the batch results. See the code for #get_picture or #fql_multiquery for examples. (Not needed in regular calls; you’ll probably rarely use this.)

Returns:

  • the result from Facebook

Raises:



467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/koala/api/graph_api.rb', line 467

def graph_call(path, args = {}, verb = "get", options = {}, &post_processing)
  result = api(path, args, verb, options) do |response|
    error = check_response(response.status, response.body)
    raise error if error
  end

  # turn this into a GraphCollection if it's pageable
  result = GraphCollection.evaluate(result, self)

  # now process as appropriate for the given call (get picture header, etc.)
  post_processing ? post_processing.call(result) : result
end

#put_comment(id, message, options = {}, &block) ⇒ Object

Comment on a given object. Convenience method equivalent to put_connection(id, “comments”).

To delete comments, use delete_object(comment_id). To get comments, use get_connections(object, “likes”).

Parameters:

  • message

    the comment to write

  • id

    the object ID (string or number)

  • options (defaults to: {})

    request-related options for Koala and Faraday. See github.com/arsduo/koala/wiki/HTTP-Services for additional options.

Returns:

  • a hash containing the new object’s id



262
263
264
265
# File 'lib/koala/api/graph_api.rb', line 262

def put_comment(id, message, options = {}, &block)
  # Writes the given comment on the given post.
  put_connections(id, "comments", {:message => message}, options, &block)
end

#put_connections(id, connection_name, args = {}, options = {}, &block) ⇒ Object

Note:

to access connections like /user_id/CONNECTION/other_user_id, simply pass “CONNECTION/other_user_id” as the connection_name

Write an object to the Graph for a specific user. See Facebook’s documentation for all the supported writeable objects.

Most write operations require extended permissions. For example, publishing wall posts requires the “publish_stream” permission. See developers.facebook.com/docs/authentication/ for details about extended permissions.

Examples:

graph.put_connections("me", "feed", :message => "Hello, world")
=> writes "Hello, world" to the active user's wall

Parameters:

  • id

    the object ID (string or number)

  • connection_name

    what

  • args (defaults to: {})

    any additional arguments

  • options (defaults to: {})

    request-related options for Koala and Faraday. See github.com/arsduo/koala/wiki/HTTP-Services for additional options.

Returns:

  • a hash containing the new object’s id

Raises:



144
145
146
147
148
# File 'lib/koala/api/graph_api.rb', line 144

def put_connections(id, connection_name, args = {}, options = {}, &block)
  # Posts a certain connection
  raise AuthenticationError.new(nil, nil, "Write operations require an access token") unless @access_token
  graph_call("#{id}/#{connection_name}", args, "post", options, &block)
end

#put_like(id, options = {}, &block) ⇒ Object

Like a given object. Convenience method equivalent to put_connections(id, “likes”).

To get a list of a user’s or object’s likes, use get_connections(id, “likes”).

Parameters:

Returns:

  • a hash containing the new object’s id



277
278
279
280
# File 'lib/koala/api/graph_api.rb', line 277

def put_like(id, options = {}, &block)
  # Likes the given post.
  put_connections(id, "likes", {}, options, &block)
end

#put_object(parent_object, connection_name, args = {}, options = {}, &block) ⇒ Object

Note:

put_object is (for historical reasons) the same as put_connections. Please use put_connections; in a future version of Koala (2.0?), put_object will issue a POST directly to an individual object, not to a connection.

Write an object to the Graph for a specific user.

See Also:



84
85
86
# File 'lib/koala/api/graph_api.rb', line 84

def put_object(parent_object, connection_name, args = {}, options = {}, &block)
  put_connections(parent_object, connection_name, args, options, &block)
end

#put_picture(*picture_args, &block) ⇒ Object

Note:

to access the media after upload, you’ll need the user_photos or user_videos permission as appropriate.

Upload a photo.

This can be called in multiple ways:

put_picture(file, [content_type], ...)
put_picture(path_to_file, [content_type], ...)
put_picture(picture_url, ...)

You can also pass in uploaded files directly from Rails or Sinatra. See the Koala wiki for more information.

Examples:

put_picture(file, content_type, {:message => "Message"}, 01234560)
put_picture(params[:file], {:message => "Message"})
# with URLs, there's no optional content type field
put_picture(picture_url, {:message => "Message"}, my_page_id)

Parameters:

Returns:

  • a hash containing the new object’s id



210
211
212
# File 'lib/koala/api/graph_api.rb', line 210

def put_picture(*picture_args, &block)
  put_connections(*parse_media_args(picture_args, "photos"), &block)
end

#put_video(*video_args, &block) ⇒ Object

Upload a video. Functions exactly the same as put_picture.

See Also:



216
217
218
219
220
# File 'lib/koala/api/graph_api.rb', line 216

def put_video(*video_args, &block)
  args = parse_media_args(video_args, "videos")
  args.last[:video] = true
  put_connections(*args, &block)
end

#put_wall_post(message, attachment = {}, target_id = "me", options = {}, &block) ⇒ Object

Write directly to the user’s wall. Convenience method equivalent to put_connections(id, “feed”).

To get wall posts, use get_connections(user, “feed”) To delete a wall post, use delete_object(post_id)

Examples:

@api.put_wall_post("Hello there!", {
  "name" => "Link name"
  "link" => "http://www.example.com/",
  "caption" => "{*actor*} posted a new review",
  "description" => "This is a longer description of the attachment",
  "picture" => "http://www.example.com/thumbnail.jpg"
})

Parameters:

  • message

    the message to write for the wall

  • attachment (defaults to: {})

    a hash describing the wall post (see the / stream attachments documentation.)

  • target_id (defaults to: "me")

    the target wall

  • options (defaults to: {})

    request-related options for Koala and Faraday. See github.com/arsduo/koala/wiki/HTTP-Services for additional options.

Returns:

  • a hash containing the new object’s id

See Also:



246
247
248
# File 'lib/koala/api/graph_api.rb', line 246

def put_wall_post(message, attachment = {}, target_id = "me", options = {}, &block)
  put_connections(target_id, "feed", attachment.merge({:message => message}), options, &block)
end

#search(search_terms, args = {}, options = {}, &block) ⇒ Koala::Facebook::API::GraphCollection

Search for a given query among visible Facebook objects. See Facebook documentation for more information.

Parameters:

  • search_terms

    the query to search for

  • args (defaults to: {})

    additional arguments, such as type, fields, etc.

  • options (defaults to: {})

    request-related options for Koala and Faraday. See github.com/arsduo/koala/wiki/HTTP-Services for additional options.

Returns:



305
306
307
308
# File 'lib/koala/api/graph_api.rb', line 305

def search(search_terms, args = {}, options = {}, &block)
  args.merge!({:q => search_terms}) unless search_terms.nil?
  graph_call("search", args, "get", options, &block)
end

#set_app_restrictions(app_id, restrictions_hash, args = {}, options = {}, &block) ⇒ Object



386
387
388
# File 'lib/koala/api/graph_api.rb', line 386

def set_app_restrictions(app_id, restrictions_hash, args = {}, options = {}, &block)
  graph_call(app_id, args.merge(:restrictions => MultiJson.dump(restrictions_hash)), "post", options, &block)
end