I'm trying to get the potential reach from the Facebook Marketing API using Ruby on Rails 5. I found the Ruby SDK here but I can't see the sample codes nor the functions that I need for getting the data that I want. I also found this post which was based on Python and tried to convert the language to Ruby which led me to this code:
require "facebook_ads"
class FacebookApi
attr_reader :ad_instance
def initialize(opts={})
@ad_instance = FacebookAds::AdAccount.get("act_#{opts[:account_id]}")
raise 'Account ID Key must be provided' unless opts[:account_id]
end
def get_target()
targeting_spec = {
'geo_locations': {
'countries': ['US'],
},
'age_min': 20,
'age_max': 40,
}
params = {
'targeting_spec': targeting_spec,
}
@ad_instance.get_reach_estimate(params: params)
end
end
However, the function get_reach_estimate is not found.
I also tried emulating the sample cURL commands instead and came up with the following test script:
require 'net/http'
require 'uri'
require "erb"
include ERB::Util
class FacebookApi
def get_target()
account_id = <ACCOUNT_ID>
access_token = <USER_ACCESS_TOKEN_WITH_ADS_MANAGEMENT_PRIVILEGE>
uri = URI.parse("https://graph.facebook.com/v2.10/act_#{account_id}/reachestimate")
request = Net::HTTP::Post.new(uri)
request.set_form_data(
"access_token" => access_token,
"targeting_spec" => url_encode("{\"geo_locations\": {\"countries\":[\"US\"]}, \"age_min\": 20, \"age_max\": 40}")
)
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
puts response.code
puts response.body
end
end
Please take note that I'm using the actual account ID and access token in my code. Just hiding it here. So the code above now returns the following error:
{
"error": {
"message": "Unsupported post request. Object with ID <ACCOUNT_ID> does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
"type": "GraphMethodException",
"code": 100,
"fbtrace_id": "ESJks9/KxJC"
}
}
I'm sure I added the ad_management access to my access token. I also tried removing the prefix act_ in the URI but same result. I'm hitting a dead-end right now so I would like to ask some suggestions on how to do this. Thank you very much.
Turns out, it's because of the post request. I should be using a GET request instead. Here's the working code for me with the additional interest parameter for the targeting spec.