### Batch API test suite examples Source: https://github.com/arsduo/koala/wiki/Batch-requests A comprehensive set of RSpec examples demonstrating Koala's batch API capabilities, including multiple GET requests, mixed calls, picture retrieval, handling different tokens, error placement, different HTTP methods, binary file uploads, request relationships, dependencies, and error handling for bad relationships. Note the 50-request limit per batch. ```ruby before :each do @api = Koala::Facebook::API.new(my_access_token) end it "can get two results at once" do me, facebook = @api.batch do |batch_api| batch_api.get_object('me') batch_api.get_object('facebook') end me['id'].should_not be_nil facebook['id'].should_not be_nil end it 'should be able to make mixed calls inside of a batch' do me, friends = @api.batch do |batch_api| batch_api.get_object('me') batch_api.get_connections('me', 'friends') end me['id'].should_not be_nil friends.should be_an(Array) end it 'should be able to make a get_picture call inside of a batch' do pictures = @api.batch do |batch_api| batch_api.get_picture('me') end pictures.first.should_not be_empty end it "should handle requests for two different tokens" do me, insights = @api.batch do |batch_api| batch_api.get_object('me') batch_api.get_connections(@app_id, 'insights', {}, {"access_token" => @app_api.access_token}) end me['id'].should_not be_nil insights.should be_an(Array) end it "inserts errors in the appropriate place, without breaking other results" do failed_insights, koppel = @api.batch do |batch_api| batch_api.get_connections(@app_id, 'insights') batch_api.get_object("koppel", {}, {"access_token" => @app_api.access_token}) end failed_insights.should be_a(Koala::Facebook::APIError) koppel["id"].should_not be_nil end it "handles different request methods" do result = @api.put_wall_post("Hello, world, from the test suite batch API!") wall_post = result["id"] wall_post, koppel = @api.batch do |batch_api| batch_api.put_like(wall_post) batch_api.delete_object(wall_post) end end it "posts binary files" do file = File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "beach.jpg")) Koala::Facebook::BatchOperation.instance_variable_set(:@identifier, 0) result = @api.batch do |batch_api| batch_api.put_picture(file) end @temporary_object_id = result[0]["id"] @temporary_object_id.should_not be_nil end it "posts binary files with multiple requests" do file = File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "beach.jpg")) Koala::Facebook::BatchOperation.instance_variable_set(:@identifier, 0) results = @api.batch do |batch_api| batch_api.put_picture(file) batch_api.put_picture(file, {}, "koppel") end results[0]["id"].should_not be_nil results[1]["id"].should_not be_nil end it "allows you create relationships between requests without omit_response_on_success" do results = @api.batch do |batch_api| batch_api.get_connections("me", "friends", {:limit => 5}, :batch_args => {:name => "get-friends"}) batch_api.get_objects("{result=get-friends:$.data.*.id}") end results[0].should be_nil results[1].should be_an(Hash) end it "allows you create relationships between requests with omit_response_on_success" do results = @api.batch do |batch_api| batch_api.get_connections("me", "friends", {:limit => 5}, :batch_args => {:name => "get-friends", :omit_response_on_success => false}) batch_api.get_objects("{result=get-friends:$.data.*.id}") end results[0].should be_an(Array) results[1].should be_an(Hash) end it "allows you to create dependencies" do me, koppel = @api.batch do |batch_api| batch_api.get_object("me", {}, :batch_args => {:name => "getme"}) batch_api.get_object("koppel", {}, :batch_args => {:depends_on => "getme"}) end me.should be_nil # gotcha! it's omitted because it's a successfully-executed dependency koppel["id"].should_not be_nil end it "properly handles dependencies that fail" do data, koppel = @api.batch do |batch_api| batch_api.get_connections(@app_id, 'insights', {}, :batch_args => {:name => "getdata"}) batch_api.get_object("koppel", {}, :batch_args => {:depends_on => "getdata"}) end data.should be_a(Koala::Facebook::APIError) koppel.should be_nil end it "throws an error for badly-constructed request relationships" do expect { @api.batch do |batch_api| batch_api.get_connections("me", "friends", {:limit => 5}) batch_api.get_objects("{result=i-dont-exist:$.data.*.id}") end }.to raise_exception(Koala::Facebook::APIError) end ``` -------------------------------- ### Test Users Create Source: https://github.com/arsduo/koala/blob/master/readme.md Create a test user with the specified installation status and permissions. ```APIDOC ## Test Users Create ### Description Create a test user with the specified installation status and permissions. ### Method create ### Endpoint @test_users.create ### Parameters #### Request Body - **is_app_installed** (boolean) - Required - Whether the app is installed for the test user. - **desired_permissions** (string) - Required - Comma-separated list of desired permissions. ### Response #### Success Response - **user** (hash) - The created test user object, including access_token. ### Request Example ```ruby user = @test_users.create(is_app_installed, desired_permissions) ``` ``` -------------------------------- ### Install Koala gem via command line Source: https://github.com/arsduo/koala/blob/master/readme.md Installs the Koala gem using the gem command. The [sudo|rvm] prefix indicates you may need to use sudo or rvm depending on your Ruby environment. ```bash [sudo|rvm] gem install koala ``` -------------------------------- ### Basic Graph API operations with Koala Source: https://github.com/arsduo/koala/blob/master/readme.md Demonstrates core Graph API usage: getting objects, connections, posting to feed, three-part queries, Timeline API, appsecret proof, and API versioning. Requires an access token from Facebook's Graph API Explorer. Shows both global and per-request API version specification. ```ruby require 'koala' # access_token and other values aren't required if you set the defaults as described above @graph = Koala::Facebook::API.new(access_token) profile = @graph.get_object("me") friends = @graph.get_connections("me", "friends") @graph.put_connections("me", "feed", message: "I am writing on my wall!") # Three-part queries are easy too! @graph.get_connections("me", "mutualfriends/#{friend_id}") # You can use the Timeline API: # (see https://developers.facebook.com/docs/beta/opengraph/tutorial/) @graph.put_connections("me", "namespace:action", object: object_url) # For extra security (recommended), you can provide an appsecret parameter, # tying your access tokens to your app secret. # (See https://developers.facebook.com/docs/reference/api/securing-graph-api/ # You may need to turn on 'Require proof on all calls' in the advanced section # of your app's settings when doing this. @graph = Koala::Facebook::API.new(access_token, app_secret) # Facebook is now versioning their API. # If you don't specify a version, Facebook # will default to the oldest version your app is allowed to use. # See https://developers.facebook.com/docs/apps/versions for more information. # # You can specify version either globally: Koala.config.api_version = "v2.0" # or on a per-request basis @graph.get_object("me", {}, api_version: "v2.0") ``` -------------------------------- ### Paging through Graph API results with GraphCollection Source: https://github.com/arsduo/koala/blob/master/readme.md Shows how to iterate over a GraphCollection returned by get_connections, fetch the next page, and get parameters for the next page URL. Useful for handling paginated results and storing page state across requests. ```ruby # Returns the feed items for the currently logged-in user as a GraphCollection feed = @graph.get_connections("me", "feed") feed.each {|f| do_something_with_item(f) } # it's a subclass of Array next_feed = feed.next_page # You can also get an array describing the URL for the next page: [path, arguments] # This is useful for storing page state across multiple browser requests next_page_params = feed.next_page_params page = @graph.get_page(next_page_params) ``` -------------------------------- ### Realtime Updates List Subscriptions Source: https://github.com/arsduo/koala/blob/master/readme.md Get an array of your current subscriptions (one hash for each object you've subscribed to). ```APIDOC ## Realtime Updates List Subscriptions ### Description Get an array of your current subscriptions (one hash for each object you've subscribed to). ### Method list_subscriptions ### Endpoint @updates.list_subscriptions ### Response #### Success Response - **subscriptions** (array) - Array of subscription hashes. ### Request Example ```ruby @updates.list_subscriptions ``` ``` -------------------------------- ### Slicing requests into groups of 50 Source: https://github.com/arsduo/koala/wiki/Batch-requests Example from test_users.rb showing how to comply with Facebook's 50-request limit by using each_slice(50) to process a list of users in batches, deleting each user's ID via batch_api.delete_object. ```ruby # example from test_users.rb test_user_list.each_slice(50) do |users| self.api.batch(options) {|batch_api| users.each {|u| batch_api.delete_object(u["id"]) }} end ``` -------------------------------- ### Initialize RealtimeUpdates Source: https://github.com/arsduo/koala/blob/master/readme.md Create a RealtimeUpdates instance to interact with your applications. Supports the defaults as described above. ```ruby # This class also supports the defaults as described above @updates = Koala::Facebook::RealtimeUpdates.new(app_id: app_id, secret: secret) ``` -------------------------------- ### Set SSL certificate globally and per-request timeout Source: https://github.com/arsduo/koala/blob/master/readme.md Configure Faraday HTTP options globally via Koala.http_service.http_options or per-request by passing a request options hash. The global example sets an SSL certificate path to avoid Net::HTTP errors; the per-request example sets a timeout of 10 seconds. ```ruby # Set an SSL certificate to avoid Net::HTTP errors Koala.http_service.http_options = { ssl: { ca_path: "/etc/ssl/certs" } } # or on a per-request basis @api.get_object(id, args_hash, { request: { timeout: 10 } }) ``` -------------------------------- ### Get app access token Source: https://github.com/arsduo/koala/blob/master/readme.md Get your application's own access token, which can be used without a user session for subscriptions and certain other requests. ```ruby @oauth = Koala::Facebook::OAuth.new(app_id, app_secret, callback_url) @oauth.get_app_access_token ``` -------------------------------- ### OAuth App Access Token Source: https://github.com/arsduo/koala/blob/master/readme.md Get your application's own access token, which can be used without a user session for subscriptions and certain other requests. ```APIDOC ## OAuth App Access Token ### Description Get your application's own access token, which can be used without a user session for subscriptions and certain other requests. ### Method get_app_access_token ### Endpoint @oauth.get_app_access_token ### Parameters #### Constructor - **app_id** (string) - Required - Your application's ID. - **app_secret** (string) - Required - Your application's secret. - **callback_url** (string) - Required - The callback URL. ### Response #### Success Response - **access_token** (string) - The application access token. ### Request Example ```ruby @oauth = Koala::Facebook::OAuth.new(app_id, app_secret, callback_url) @oauth.get_app_access_token ``` ``` -------------------------------- ### Authenticate as page and use Graph API Source: https://github.com/arsduo/koala/wiki/Acting-as-a-Page Use the page token to create a Koala API object and perform Graph API calls as the page. Requires publish_pages permission for posting actions. Examples include getting the page's info, feed, posting to wall, posting links, and posting pictures. ```ruby @page_graph = Koala::Facebook::API.new(page_token) @page_graph.get_object('me') # I'm a page @page_graph.get_connection('me', 'feed') # the page's wall @page_graph.put_wall_post('post on page wall') # post as page, requires new publish_pages permission @page_graph.put_connections('me', 'feed', :message => message, :link => link_url) #post as link to page @page_graph.put_picture(picture_url, {:message => "hello"}, page_id) #post as picture with caption ``` -------------------------------- ### Rate Limit Information via APIError Source: https://github.com/arsduo/koala/blob/master/readme.md Access Facebook rate limit information through the Facebook::APIError object. ```APIDOC ## Rate Limit Information via APIError ### Description Access Facebook rate limit information through the Facebook::APIError object. ### Method fb_buc_usage, fb_ada_usage, fb_app_usage ### Endpoint error.fb_buc_usage, error.fb_ada_usage, error.fb_app_usage ### Response #### Success Response - **fb_buc_usage** - Business use case usage. - **fb_ada_usage** - Ad account usage. - **fb_app_usage** - App usage. ### Request Example ```ruby error.fb_buc_usage error.fb_ada_usage error.fb_app_usage ``` ``` -------------------------------- ### Realtime Updates Meet Challenge Source: https://github.com/arsduo/koala/blob/master/readme.md Static method to respond to Facebook servers' verification of your callback URLs. Returns the hub.challenge parameter in params if the verify token in params matches verify_token. ```APIDOC ## Realtime Updates Meet Challenge ### Description Static method to respond to Facebook servers' verification of your callback URLs. Returns the hub.challenge parameter in params if the verify token in params matches verify_token. ### Method meet_challenge ### Endpoint Koala::Facebook::RealtimeUpdates.meet_challenge ### Parameters #### Request Body - **params** (hash) - Required - The parameters from the verification request. - **verify_token** (string) - Required - The verify token to match. ### Response #### Success Response - **hub.challenge** (string) - The challenge parameter if verification succeeds. ### Request Example ```ruby Koala::Facebook::RealtimeUpdates.meet_challenge(params, your_verify_token) ``` ``` -------------------------------- ### Parse signed request Source: https://github.com/arsduo/koala/blob/master/readme.md Parse a signed request string for apps building on Facebook. ```ruby @oauth.parse_signed_request(signed_request_string) ``` -------------------------------- ### Rate Limit Hook Configuration Source: https://github.com/arsduo/koala/blob/master/readme.md Configure a rate limit hook to receive rate limit information. Can be set at app level or per API instance. ```APIDOC ## Rate Limit Hook Configuration ### Description Configure a rate limit hook to receive rate limit information. Can be set at app level or per API instance. ### Method rate_limit_hook ### Endpoint Koala.configure, Koala::Facebook::API.new ### Parameters #### Configuration - **rate_limit_hook** (lambda) - Required - A lambda that receives the rate limit headers. ### Response #### Success Response - **limits** (hash) - The rate limit headers. ### Request Example ```ruby Koala.configure do |config| config.rate_limit_hook = ->(limits) { limits["x-app-usage"] # {"call_count"=>0, "total_cputime"=>0, "total_time"=>0} limits["x-ad-account-usage"] # {"acc_id_util_pct"=>9.67} limits["x-business-use-case-usage"] # {"123456789012345"=>[{"type"=>"messenger", "call_count"=>1, "total_cputime"=>1, "total_time"=>1, "estimated_time_to_regain_access"=>0}]} } end # Per API configuration Koala::Facebook::API.new('', '', ->(limits) {}) ``` ``` -------------------------------- ### Run Koala test suite with bundle exec rake spec Source: https://github.com/arsduo/koala/blob/master/readme.md Run the unit tests from anywhere in the project directory. Tests use mocked responses and recorded HTTP interactions, so no Facebook credentials or network access are required. ```bash # From anywhere in the project directory: bundle exec rake spec ``` -------------------------------- ### Access rate limit info via APIError Source: https://github.com/arsduo/koala/blob/master/readme.md Access Facebook rate limit information from a Facebook::APIError object. ```ruby error.fb_buc_usage error.fb_ada_usage error.fb_app_usage ``` -------------------------------- ### Realtime Updates Unsubscribe Source: https://github.com/arsduo/koala/blob/master/readme.md Unsubscribe from updates for an object. ```APIDOC ## Realtime Updates Unsubscribe ### Description Unsubscribe from updates for an object. ### Method unsubscribe ### Endpoint @updates.unsubscribe ### Parameters #### Request Body - **object** (string) - Required - The object to unsubscribe from. ### Response #### Success Response - **result** - The unsubscribe result. ### Request Example ```ruby @updates.unsubscribe("user") ``` ``` -------------------------------- ### Create test users Source: https://github.com/arsduo/koala/blob/master/readme.md Use the test users API to create fake users and interact with them via the Graph API. Also supports creating a network of users. ```ruby # This class also supports the defaults as described above @test_users = Koala::Facebook::TestUsers.new(app_id: id, secret: secret) user = @test_users.create(is_app_installed, desired_permissions) user_graph_api = Koala::Facebook::API.new(user["access_token"]) # or, if you want to make a whole community: @test_users.create_network(network_size, is_app_installed, common_permissions) ``` -------------------------------- ### Get access token directly with get_access_token Source: https://github.com/arsduo/koala/wiki/OAuth Combines fetching and parsing into one step. get_access_token returns just the token, while get_access_token_info also returns the expiration date. ```ruby @oauth.get_access_token(code) # => #{access_token} # or, if you want the expiration date as well: @oauth.get_access_token_info(code) # => {"expires" => #{seconds_from_now}, "access_token" => #{access_token}} ``` -------------------------------- ### Manage real-time update subscriptions Source: https://github.com/arsduo/koala/blob/master/readme.md Subscribe, list, and unsubscribe from real-time update subscriptions using the RealtimeUpdates class. ```ruby # Add/modify a subscription to updates for when the first_name or last_name fields of any of your users is changed @updates.subscribe("user", "first_name, last_name", callback_url, verify_token) # Get an array of your current subscriptions (one hash for each object you've subscribed to) @updates.list_subscriptions # Unsubscribe from updates for an object @updates.unsubscribe("user") ``` -------------------------------- ### Respond to Facebook callback verification Source: https://github.com/arsduo/koala/blob/master/readme.md Static method to respond to Facebook servers' verification of your callback URLs. Returns the hub.challenge parameter in params if the verify token matches. ```ruby # Returns the hub.challenge parameter in params if the verify token in params matches verify_token Koala::Facebook::RealtimeUpdates.meet_challenge(params, your_verify_token) ``` -------------------------------- ### Generate access token URL with url_for_access_token Source: https://github.com/arsduo/koala/wiki/OAuth Generates the URL that exchanges the OAuth code for an access token. Requires the code from the callback's GET parameters. ```ruby @oauth.url_for_access_token(code) # => "https://graph.facebook.com/oauth/access_token?client_id=#{app_id}&redirect_uri=#{callback_url}&client_secret=#{app_secret}&code=#{code}" ``` -------------------------------- ### Graph API Batch Requests Source: https://github.com/arsduo/koala/blob/master/readme.md Make multiple Graph API calls at once using Facebook's batch API. Returns an array of results as if they were called non-batch. ```APIDOC ## Graph API Batch Requests ### Description Make multiple Graph API calls at once using Facebook's batch API. Returns an array of results as if they were called non-batch. ### Method batch ### Endpoint @graph.batch ### Parameters #### Block - **batch_api** (block) - Required - The batch API object to make calls on. ### Response #### Success Response - **array** - Array of results as if they were called non-batch. ### Request Example ```ruby @graph.batch do |batch_api| batch_api.get_object('me') batch_api.put_wall_post('Making a post in a batch.') end ``` ``` -------------------------------- ### Realtime Updates Subscribe Source: https://github.com/arsduo/koala/blob/master/readme.md Add or modify a subscription to real-time updates for specified fields of an object. ```APIDOC ## Realtime Updates Subscribe ### Description Add or modify a subscription to real-time updates for specified fields of an object. ### Method subscribe ### Endpoint @updates.subscribe ### Parameters #### Request Body - **object** (string) - Required - The object to subscribe to (e.g., "user"). - **fields** (string) - Required - Comma-separated list of fields to subscribe to. - **callback_url** (string) - Required - The callback URL for updates. - **verify_token** (string) - Required - The verify token for verification. ### Response #### Success Response - **subscription** - The subscription result. ### Request Example ```ruby @updates.subscribe("user", "first_name, last_name", callback_url, verify_token) ``` ``` -------------------------------- ### Batch API with post-processing blocks Source: https://github.com/arsduo/koala/blob/master/readme.md Use post-processing blocks inside a batch call to consume data in place, avoiding pulling results apart from a long list of array entries. Assumes database fields 'about_me' and 'photos'. ```ruby @graph.batch do |batch_api| # Assuming you have database fields "about_me" and "photos" batch_api.get_object('me') {|me| self.about_me = me } batch_api.get_connections('me', 'photos') {|photos| self.photos = photos } end ``` -------------------------------- ### Example Facebook Cookie Hash for OAuth Verification Source: https://github.com/arsduo/koala/wiki/OAuth Shows the structure of the fbs_#{app_id} cookie created by Facebook's JavaScript library. The cookie contains a string with inner quotes holding all information needed to verify the user. ```ruby {"fbs_190889632882"=>"\"access_token=190889632882|2.U25mFtixF8Pqth45AtnsBQ__.3600.1272909600-2905623| DNjswq9QfKDrP60TY76Tv8GxCc.&expires=1272909600&secret=QR_id58vqV_qW7MnfJlmLw__& session_key=2.U25mFtixF8Pqth45AtnsBQ__.3600.1272909600-2905623& sig=a76960c0c3669470f7ca53b53e034ac4&uid=2905623\"", [other cookies]...} ``` -------------------------------- ### Get Application Access Token with Koala::Facebook::OAuth Source: https://github.com/arsduo/koala/wiki/OAuth Retrieves the app's access token for managing realtime updates and sessionless activities. The token does not expire, but you can still get its hash with get_app_access_token_info. ```ruby @oauth = Koala::Facebook::OAuth.new(app_id, app_secret) @oauth.get_app_access_token # => #{app_access_token} # these don't expire, but you can still get the hash with get_app_access_token_info ``` -------------------------------- ### Parse signed request with Koala::Facebook::OAuth Source: https://github.com/arsduo/koala/wiki/OAuth Decode and validate a Facebook signed request for canvas or tab apps. Requires enabling signed_request in the advanced app configurations. The first example uses a dummy app ID and secret 'secret' and returns the payload. The second example uses a real secret and will fail because the signed params are over an hour old, but would produce the shown output. ```ruby # http://developers.facebook.com/docs/authentication/signed_request/ # in Rails, this would usually be available as params[:signed_request] signed_request = "vlXgu64BQGFSQrY0ZcJBZASMvYvTHu9GQ0YM9rjPSso.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsIjAiOiJwYXlsb2FkIn0" @oauth = Koala::Facebook::OAuth.new(12345, "secret") # example secret is 'secret', app ID doesn't matter @oauth.parse_signed_request(signed_request) # => {"algorithm"=>"HMAC-SHA256", "0"=>"payload"} # Example request from http://developers.facebook.com/docs/authentication/canvas/encryption_proposal # note: this support is available as of 1.0 beta signed_request = "LONG_STRING_OF_CHARACTERS" # dummy app ID, secret provided by Facebook @oauth = Koala::Facebook::OAuth.new(12345, "13750c9911fec5865d01f3bd00bdf4db") @oauth.parse_signed_request(signed_request) # note: this will fail for you because the signed params are over an hour old, but it would produce: # => {"iv"=>"fDLJCW-yiXmuNa24eSarJg", "payload"=>"LONG_STRING_OF_CHARACTERS", "algorithm"=>"AES-256-CBC HMAC-SHA256", "issued_at"=>1287601988} ``` -------------------------------- ### Retrieve page access tokens Source: https://github.com/arsduo/koala/wiki/Acting-as-a-Page Get a collection of all managed pages via 'me/accounts' or retrieve a single page access token for a given page_id. The collection hashes include page id, name, category, access token, and permissions. ```ruby # retrieve collection for all your managed pages: returns collection of hashes with page id, name, category, access token and permissions pages = @user_graph.get_connections('me', 'accounts') # get access token for first page first_page_token = pages.first['access_token'] # or: retrieve access_token for a given page_id page_token = @user_graph.get_page_access_token(page_id) ``` -------------------------------- ### Add Koala gem to Gemfile Source: https://github.com/arsduo/koala/blob/master/readme.md Adds the Koala gem to a Bundler-managed project. Use this in your Gemfile to include Koala as a dependency. ```ruby gem "koala" ``` -------------------------------- ### Configure rate_limit_hook Source: https://github.com/arsduo/koala/blob/master/readme.md Set a rate_limit_hook at app level or per API configuration to receive rate limit information. The hook receives a limits hash with keys like 'x-app-usage', 'x-ad-account-usage', and 'x-business-use-case-usage'. ```ruby # App level configuration Koala.configure do |config| config.rate_limit_hook = ->(limits) { limits["x-app-usage"] # {"call_count"=>0, "total_cputime"=>0, "total_time"=>0} limits["x-ad-account-usage"] # {"acc_id_util_pct"=>9.67} limits["x-business-use-case-usage"] # {"123456789012345"=>[{"type"=>"messenger", "call_count"=>1, "total_cputime"=>1, "total_time"=>1, "estimated_time_to_regain_access"=>0}]} } end # Per API configuration Koala::Facebook::API.new('', '', ->(limits) {}) ``` -------------------------------- ### Post-processing block with get_object Source: https://github.com/arsduo/koala/blob/master/readme.md Pass a block to a Graph API method to modify the returned result. Here, only the 'education' portion of the profile is returned. ```ruby education = @graph.get_object("me") { |data| data['education'] } # returned value only contains the "education" portion of the profile ``` -------------------------------- ### Verify Cookies and Get User Info with get_user_info_from_cookies Source: https://github.com/arsduo/koala/wiki/OAuth Validates the fbs_#{app_id} cookie and returns a hash with the user's session key, expiry, UID, signature, secret, and access token. Returns nil if the cookies are invalid (expired or falsified). ```ruby @oauth.get_user_info_from_cookies(cookies) # => {"session_key"=>"2.U25mFtixF8Pqth45AtnsBQ__.3600.1272909600-2905623", # "expires"=>"1272909600", "uid"=>"2905623", "sig"=>"a76960c0c3669470f7ca53b53e034ac4", # "secret"=>"QR_id58vqV_qW7MnfJlmLw__", "access_token"=>"190889632882|2.U25mFtixF8Pqth45AtnsBQ__. # 3600.1272909600-2905623|DNjswq9Q-fKDrP60TY76Tv8GxCc." ``` -------------------------------- ### Configure Koala globally with access tokens Source: https://github.com/arsduo/koala/blob/master/readme.md Sets global Koala configuration for access tokens, app access token, app ID, and app secret. Typically placed in config/initializers/koala.rb in Rails. Note: this configuration is not threadsafe. ```ruby # In Rails, you could put this in config/initializers/koala.rb Koala.configure do |config| config.access_token = MY_TOKEN config.app_access_token = MY_APP_ACCESS_TOKEN config.app_id = MY_APP_ID config.app_secret = MY_APP_SECRET # See Koala::Configuration for more options, including details on how to send requests through # your own proxy servers. end ``` -------------------------------- ### Batch API calls with Koala Source: https://github.com/arsduo/koala/blob/master/readme.md Use Facebook's batch API to make multiple Graph API calls at once. The block receives a batch_api object; results are returned as an array as if they were called non-batch. ```ruby # Returns an array of results as if they were called non-batch @graph.batch do |batch_api| batch_api.get_object('me') batch_api.put_wall_post('Making a post in a batch.') end ``` -------------------------------- ### Graph API Post-Processing Blocks Source: https://github.com/arsduo/koala/blob/master/readme.md Pass a post-processing block to any of Koala's Graph API methods to modify the result or consume data in place. Useful for batch calls to avoid pulling results apart from a long list of array entries. ```APIDOC ## Graph API Post-Processing Blocks ### Description Pass a post-processing block to any of Koala's Graph API methods to modify the result or consume data in place. Useful for batch calls to avoid pulling results apart from a long list of array entries. ### Method block ### Endpoint @graph.get_object, @graph.get_connections ### Parameters #### Block - **block** (block) - Required - The post-processing block to apply to the result. ### Response #### Success Response - **result** - The modified result or the consumed data. ### Request Example ```ruby education = @graph.get_object("me") { |data| data['education'] } # returned value only contains the "education" portion of the profile ``` ```ruby @graph.batch do |batch_api| # Assuming you have database fields "about_me" and "photos" batch_api.get_object('me') {|me| self.about_me = me } batch_api.get_connections('me', 'photos') {|photos| self.photos = photos } end ``` ``` -------------------------------- ### Create Koala OAuth helper Source: https://github.com/arsduo/koala/wiki/OAuth Initializes a Koala::Facebook::OAuth object with your app's API key, app secret, and optional callback URL. The callback_url is optional here but must be provided in later calls if omitted. ```ruby @oauth = Koala::Facebook::OAuth.new(api_key, app_secret, callback_url) # => # ``` -------------------------------- ### Pass additional parameters to put_picture and put_video Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos Shows how to pass Facebook arguments, user/album ID, and HTTP options. Videos use title instead of caption. See Graph API photo and video references for all available parameters. ```ruby @graph.put_picture(file, content_type, facebook_arguments = {}, user_or_album_id, http_options = {}) # so for instance @graph.put_picture(file, content_type, {:caption => "My upload message"}, "me") @graph.put_picture(params[:file], {:caption => "Message"}, my_album_id) # videos take title instead of caption params @graph.put_video(file, content_type, {:title => "My upload message for video"}, "me") ``` -------------------------------- ### Set Faraday adapter for IO uploads Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos To upload StringIO objects, you need an adapter that supports uploading IOs. Set Faraday.default_adapter to :net_http or another compatible library. ```ruby Faraday.default_adapter = :net_http # or whichever library you want ``` -------------------------------- ### Instantiate Koala OAuth Helper for Cookie Verification Source: https://github.com/arsduo/koala/wiki/OAuth Creates a Koala::Facebook::OAuth instance using your app ID and secret, which is required before verifying cookies. ```ruby @oauth = Koala::Facebook::OAuth.new(app_id, app_secret) # => # ``` -------------------------------- ### Upload photo or video with put_picture and put_video Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos Shows the various argument types accepted by put_picture and put_video: file path, File object, Rails 3 upload, Sinatra hash, and StringIO. Requires publish_actions permission; user_photos or user_videos needed to access after upload. ```ruby @graph = Koala::Facebook::API.new(access_token) # You can supply several different arguments to put_picture and put_video: # 1) Path to a photo @graph.put_picture(path_to_my_file) # 2) Upload a file directly @graph.put_picture(file_class_object) # 3) Rails 3 file uploads (ActionDispatch::Http::UploadedFile) @graph.put_picture(params[:file]) # 4) Sinatra file uploads (Hash) @graph.put_picture(file_hash) # 5) StringIO (1.2beta3) @graph.put_picture(io, content_type) # put_video has the same syntax options available @graph.put_video(path_to_my_video) @graph.put_video(file_class_object) @graph.put_video(params[:file]) @graph.put_video(file_hash) ``` -------------------------------- ### Fetch and parse token string Source: https://github.com/arsduo/koala/wiki/OAuth Fetches the raw token string from Facebook and parses it into a hash with "expires" and "access_token" keys. The result includes the expiration time in seconds from now. ```ruby result = @oauth.fetch_token_string(code) # => "access_token=#{access_token}&expires=#{seconds_from_now}" @oauth.parse_token_string(result) # => {"expires" => #{seconds_from_now}, "access_token" => #{access_token}} ``` -------------------------------- ### Authenticate as user with manage_pages permission Source: https://github.com/arsduo/koala/wiki/Acting-as-a-Page Create a Koala API object using a user access token that has the manage_pages permission (and possibly publish_pages or others depending on the task). This is the first step before retrieving page access tokens. ```ruby @user_graph = Koala::Facebook::API.new(user_access_token) ``` -------------------------------- ### Upload Ad Images with put_connections Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos Facebook Ad Images cannot be uploaded by URL, so you must read the image data and Base64-encode it. Uses put_connections with 'act_X' as the ad account ID and 'adimages' endpoint. ```ruby require 'open-uri' img_data = open(my_post.image.url :medium).read img = @graph.put_connections('act_X', 'adimages', bytes: Base64.encode64(img_data)) ``` -------------------------------- ### put_connections (Ad Images) Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos Uploads Facebook Ad Images using the put_connections method. Requires base64-encoded image data and cannot be done by URL. ```APIDOC ## put_connections (Ad Images) ### Description Uploads Facebook Ad Images using the put_connections method. Requires base64-encoded image data and cannot be done by URL. ### Method POST ### Endpoint `@graph.put_connections('act_X', 'adimages', bytes: Base64.encode64(img_data))` ### Parameters #### Path Parameters - **act_X** (String) - Required - The ad account ID. - **adimages** (String) - Required - The connection type for ad images. #### Request Body - **bytes** (String) - Required - The base64-encoded image data. ### Request Example ```ruby require 'open-uri' img_data = open(my_post.image.url :medium).read img = @graph.put_connections('act_X', 'adimages', bytes: Base64.encode64(img_data)) ``` ``` -------------------------------- ### Conditionally toggle between live and mocked responses Source: https://github.com/arsduo/koala/wiki/Using-Koala-with-mockfacebook Wrap the Koala HTTPService override in a conditional (e.g., ENV["MOCK"]) to toggle between live and mocked responses. The comment '# module Koala...' indicates where the override block goes. ```ruby if ENV["MOCK"] # or your preferred trigger # module Koala... end ``` -------------------------------- ### Generate OAuth code URL with url_for_oauth_code Source: https://github.com/arsduo/koala/wiki/OAuth Generates the authorization URL for obtaining an OAuth code. Accepts a hash with :permissions (array or comma-separated string), :callback, :state (recommended for CSRF protection), and :display options. ```ruby @oauth.url_for_oauth_code # => "https://graph.facebook.com/oauth/authorize?client_id=#{app_id}&redirect_uri=#{callback_url}" @oauth.url_for_oauth_code(:permissions => "publish_actions") # => "https://graph.facebook.com/oauth/authorize?client_id=#{app_id}&redirect_uri=#{callback_url}&scope=publish_actions" # you can provide your own token to protect against cross-site request forgery (CSRF) # this is highly recommended # see https://developers.facebook.com/docs/howtos/login/server-side-login/ @oauth.url_for_oauth_code(:permissions => "publish_actions", :state => "RANDOMSTRING") # => "https://graph.facebook.com/oauth/authorize?client_id=#{app_id}&redirect_uri=#{callback_url}&scope=publish_stream&state=SOMERANDOMSTRING" ``` -------------------------------- ### Override Koala HTTPService server to point to mockfacebook Source: https://github.com/arsduo/koala/wiki/Using-Koala-with-mockfacebook Add this snippet to your spec_helper to make Koala use mockfacebook's local HTTP server at http://localhost:8000 instead of the live Facebook API. mockfacebook does not yet support the complete Facebook API, so check its documentation for available features. ```ruby module Koala module HTTPService def self.server(options = {}) "http://localhost:8000" end end end ``` -------------------------------- ### Specify display option for OAuth code URL Source: https://github.com/arsduo/koala/wiki/OAuth Adds a :display option to the OAuth code URL to choose the form factor of the page the user is redirected to, such as "touch". ```ruby @oauth.url_for_oauth_code(:display => "touch") # => "https://graph.facebook.com/oauth/authorize?client_id=#{app_id}&redirect_uri=#{callback_url}&display=touch" ``` -------------------------------- ### Supply content type for put_picture Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos For paths and File objects, you can pass a content type as the second argument. If omitted, Koala attempts to detect it via MIME::Types or file extension; IO objects or undescriptive filenames may require explicit content type. ```ruby @graph.put_picture(file_with_weird_extension, content_type) ``` -------------------------------- ### Logging to a file with Koala::Utils.logger Source: https://github.com/arsduo/koala/wiki/Debugging Send Koala logs to a file by setting Koala::Utils.logger to a Logger instance. Note: doing this will set the level to DEBUG. ```ruby Koala::Utils.logger = Logger.new("path/to/log") ``` -------------------------------- ### Using a custom logger with Koala::Utils.logger Source: https://github.com/arsduo/koala/wiki/Debugging Use a custom logger with Koala by assigning it to Koala::Utils.logger. The logger must respond to #debug, #info, #warn, #error, #fatal, and #level. ```ruby Koala::Utils.logger = MyCustomLogger.new ``` -------------------------------- ### put_video Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos Uploads a video to Facebook. Supports the same syntax options as put_picture, including file paths, file objects, uploaded files, and hashes. Takes a title parameter instead of caption. ```APIDOC ## put_video ### Description Uploads a video to Facebook. Supports the same syntax options as put_picture, including file paths, file objects, uploaded files, and hashes. Takes a title parameter instead of caption. ### Method PUT ### Endpoint `@graph.put_video(file, content_type, facebook_arguments = {}, user_or_album_id, http_options = {})` ### Parameters #### Request Body - **file** (String/File/IO/Hash) - Required - The video to upload. Can be a path to a file, a file class object, an uploaded file, or a hash. - **content_type** (String) - Optional - The content type of the file. If not provided, it will be detected automatically using MIME::Types or file extension. - **facebook_arguments** (Hash) - Optional - Additional Facebook parameters such as title. - **user_or_album_id** (String/Integer) - Optional - The ID of the user or album to upload to. - **http_options** (Hash) - Optional - Additional HTTP options. ### Response #### Success Response (200) - **id** (String) - The Facebook UID for the uploaded video. ### Request Example ```ruby @graph.put_video(file, content_type, {:title => "My upload message for video"}, "me") ``` ``` -------------------------------- ### Logging messages with Koala::Utils Source: https://github.com/arsduo/koala/wiki/Debugging Use these methods to log messages at various levels when debugging Koala requests. Enable logging by setting Koala::Utils.level = Logger::DEBUG. ```ruby Koala::Utils.debug "message" Koala::Utils.info "message" Koala::Utils.warn "message" Koala::Utils.error "message" Koala::Utils.fatal "message" ``` -------------------------------- ### Setting the logger level with Koala::Utils.level Source: https://github.com/arsduo/koala/wiki/Debugging Set the logging level for Koala's Logger utility. Use Logger::DEBUG to enable logging, or other levels to filter messages. ```ruby Koala::Utils.level = Logger::DEBUG Koala::Utils.level = Logger::INFO Koala::Utils.level = Logger::WARN Koala::Utils.level = Logger::ERROR Koala::Utils.level = Logger::FATAL ``` -------------------------------- ### Upload photo to a specific album with put_picture Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos By default, put_picture uploads to the logged-in user's profile (Facebook may create an app album). Pass album ID as third parameter to upload to a specific album; returns a hash with the photo's Facebook UID. Facebook may limit which albums an app can post to. ```ruby @graph.put_picture(file, { "caption" => "This is the photo caption" }, 123456) # => { "id" => FACEBOOK_UID_FOR_THE_PHOTO } ``` -------------------------------- ### put_picture Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos Uploads a photo to Facebook. Supports various input types including file paths, file objects, uploaded files, hashes, and IO objects. Additional parameters can be passed for captions and target albums. ```APIDOC ## put_picture ### Description Uploads a photo to Facebook. Supports various input types including file paths, file objects, uploaded files, hashes, and IO objects. Additional parameters can be passed for captions and target albums. ### Method PUT ### Endpoint `@graph.put_picture(file, content_type, facebook_arguments = {}, user_or_album_id, http_options = {})` ### Parameters #### Request Body - **file** (String/File/IO/Hash) - Required - The photo to upload. Can be a path to a file, a file class object, an uploaded file, a hash, or an IO object. - **content_type** (String) - Optional - The content type of the file. If not provided, it will be detected automatically using MIME::Types or file extension. - **facebook_arguments** (Hash) - Optional - Additional Facebook parameters such as caption. - **user_or_album_id** (String/Integer) - Optional - The ID of the user or album to upload to. Defaults to the current user's profile. - **http_options** (Hash) - Optional - Additional HTTP options. ### Response #### Success Response (200) - **id** (String) - The Facebook UID for the uploaded photo. ### Request Example ```ruby @graph.put_picture(file, content_type, {:caption => "My upload message"}, "me") @graph.put_picture(params[:file], {:caption => "Message"}, my_album_id) ``` ### Response Example ```ruby { "id" => FACEBOOK_UID_FOR_THE_PHOTO } ``` ```