简体   繁体   中英

FB Ads API (#17) User request limit reached

I am working on Facebook ads api to get the account Campaign data.What I am doing here is I get list of all campaigns and doing forloop of each campaign get Campaign stat

$campaignSets = $account->getCampaigns(array(
      CampaignFields::ID,
      CampaignFields::NAME
));

foreach ($campaignSets as $campaign) {
      $campaign = new Campaign($campaign->id);
      $fields = array(
        InsightsFields::CAMPAIGN_NAME,
        InsightsFields::IMPRESSIONS,
        InsightsFields::UNIQUE_CLICKS,
        InsightsFields::REACH,
        InsightsFields::SPEND,
        InsightsFields::TOTAL_ACTIONS,
        InsightsFields::TOTAL_ACTION_VALUE
      );
      $params = array(
        'date_preset' => InsightsPresets::TODAY
      );
                $insights = $campaign->getInsights($fields, $params);
}

when executing above code I am getting error as (#17) User request limit reached.

Can anyone help me how to solve this kind of error?

Thanks, Ronak Shah

You should consider generating a single report against the adaccount which returns insights for all of your campaigns, this should reduce the number of requests required significantly.

Cursor::setDefaultUseImplicitFetch(true);

$account = new AdAccount($account_id);
$fields = array(
  InsightsFields::CAMPAIGN_NAME,
  InsightsFields::CAMPAIGN_ID,
  InsightsFields::IMPRESSIONS,
  InsightsFields::UNIQUE_CLICKS,
  InsightsFields::REACH,
  InsightsFields::SPEND,
  InsightsFields::TOTAL_ACTIONS,
  InsightsFields::TOTAL_ACTION_VALUE,
);
$params = array(
  'date_preset' => InsightsPresets::TODAY,
  'level' => 'ad',
  'limit' => 1000,
);

$insights = $account->getInsights($fields, $params);
foreach($insights as $i) {
  echo $i->campaign_id.PHP_EOL;
}

If you run into API limits, your only option is to reduce calls. You can do this easily by delaying API calls. I assume you are already using a Cron Job, so implement a counter that stores the last campaign you have requested the data for. When the Cron Job runs again, request the data of the next 1-x campaign data (you have to test how many are possible per Cron Job call) and store the last one again.

Also, you should batch the API calls - it will not avoid limits, but it will be a lot faster. As fast as the slowest API call in the batch.

Add this to your code and you'll never have to worry about FB's Rate Limiting/User Limit Reached. Your script will automatically sleep as soon as you approach the limit, and then pick up from where it left after the cool down. Enjoy :)

import logging
import requests as rq

#Function to find the string between two strings or characters
def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

#Function to check how close you are to the FB Rate Limit
def check_limit():
    check=rq.get('https://graph.facebook.com/v3.3/act_'+account_number+'/insights?access_token='+my_access_token)
    call=float(find_between(check.headers['x-business-use-case-usage'],'call_count":','}'))
    cpu=float(find_between(check.headers['x-business-use-case-usage'],'total_cputime":','}'))
    total=float(find_between(check.headers['x-business-use-case-usage'],'total_time":',','))
    usage=max(call,cpu,total)
    return usage

#Check if you reached 75% of the limit, if yes then back-off for 5 minutes (put this chunk in your loop, every 200-500 iterations)
if (check_limit()>75):
    print('75% Rate Limit Reached. Cooling Time 5 Minutes.')
    logging.debug('75% Rate Limit Reached. Cooling Time 5 Minutes.')
    time.sleep(300)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM