图谱 API 版

Ad Label

API users tend to create 1000s of campaigns/ad sets/ads, and would like to have the ability to group together sets of ad objects arbitrarily. For example, an advertiser may want to track all campaigns that are targeting men or women, or track all ads that are using the same creative. Or use external data, like, track all campaigns that were created by a particular team, as a part of a particular marketing initiative.

Until now this could be achieved by overloading the name of the ad object. API developers have come up with complicated naming schemes, creating campaigns with names like “[client]-[fmp]-[autogen]-[18-34-oregon]-[custaudience-141]”, and these names are used to parse out tags.

With the introduction of Labels API, we allow developers to tag ad objects with multiple "labels" (strings). Developers can query by these labels, so they can quickly collate and query ad objects such as campaigns, ad sets, ads and creatives that belong to the same “label”.

Limits

The following are the limits on ad sets

Limit Value

Maximum number of ad labels per regular ad account

100,000 non-deleted ad labels

Maximum number of ad labels specified in the spec (to be associated with an ad object)

50 ad labels spec

读取

An AdLabel

Examples

Getting all labels within the account:

use FacebookAds\Object\AdAccount;

$account = new AdAccount('act_<AD_ACCOUNT_ID>');
$account->getAdLabels();
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.adlabel import AdLabel

account = AdAccount('act_<AD_ACCOUNT_ID>')
adlabels = account.get_ad_labels()

for adlabel in adlabels:
    print(adlabel[AdLabel.Field.name])
APINodeList<AdLabel> adLabels = new AdAccount(act_<AD_ACCOUNT_ID>, context).getAdLabels()
  .execute();
curl -G \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/act_<AD_ACCOUNT_ID>/adlabels

Getting labels associated with a given ad object:

use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;

$ad = new Ad(<AD_ID>);
$ad->read(array(
  AdFields::ADLABELS,
));
from facebookads.adobjects.ad import Ad

ad = Ad(<AD_ID>)
ad.remote_read(fields=[Ad.Field.adlabels])
Ad ad2 = new Ad(<AD_ID>, context).get()
  .requestAdlabelsField()
  .execute();
curl -G \
  -d 'fields=adlabels' \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/<AD_ID>

Getting ad objects associated with a given label

For an ad account, one can retrieve ad objects associated with an ad label. This can be achieved by:

  • for campaigns, using endpoint /campaignsbylabels
  • for ad sets, using endpoint /adsetsbylabels
  • for ads, using endpoint /adsbylabels
  • for creatives, using endpoint /adcreativesbylabels

Supported operators are ALL and ANY: for ids and label names matching, partial string matching is not supported.

curl -G \
  -d 'ad_label_ids=["<AD_LABEL_ID>"]' \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v21.0/act_<AD_ACCOUNT_ID>/adsbylabels
      

Filtering by names using {object}.adlabels on Insights edge:

use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdsInsightsFields;
use FacebookAds\Object\Values\AdsInsightsLevelValues;
use FacebookAds\Object\Values\InsightsOperators;
$account = new AdAccount('act_<AD_ACCOUNT_ID>');

$params = array(
  'level' => AdsInsightsLevelValues::AD,
  'filtering' => array(
    array(
      'field' => 'adgroup.adlabels',
      'operator' => InsightsOperators::ANY,
      'value' => array('<AD_LABEL_NAME>'),
    ),
  ),
  'time_range' => array(
    'since' => '2015-03-01',
    'until' => '2015-03-31',
  ),
);

$fields = array(
  AdsInsightsFields::INLINE_LINK_CLICKS,
  AdsInsightsFields::COST_PER_INLINE_LINK_CLICK,
  AdsInsightsFields::TOTAL_ACTIONS,
);

$stats = $account->getInsights($fields, $params);
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.adsinsights import AdsInsights

ad_account = AdAccount('act_<AD_ACCOUNT_ID>')
params = {
    'fields': [
        AdsInsights.Field.unique_clicks,
        AdsInsights.Field.ctr,
        AdsInsights.Field.total_actions,
    ],
    'level': 'ad',
    'filtering': [
        {
            'field': 'ad.adlabels',
            'operator': 'ANY',
            'value': ['<AD_LABEL_NAME>'],
        },
    ],
    'time_range': {
        'since': '2015-03-01',
        'until': '2015-03-31',
    },
}
stats = ad_account.get_insights(params=params)
print(stats)
APINodeList<AdsInsights> adsInsightss = new AdAccount(act_<AD_ACCOUNT_ID>, context).getInsights()
  .setLevel(AdsInsights.EnumLevel.VALUE_AD)
  .setFiltering("[{\"field\":\"adgroup.adlabels\",\"operator\":\"ANY\",\"value\":[\"" + <AD_LABEL_NAME> + "\"]}]")
  .setTimeRange("{\"since\":\"2015-03-01\",\"until\":\"2015-03-31\"}")
  .requestField("inline_link_clicks")
  .requestField("cost_per_inline_link_click")
  .requestField("total_actions")
  .execute();
curl -G \
  -d 'level=ad' \
  --data-urlencode 'filtering=[ 
    { 
      "field": "adgroup.adlabels", 
      "operator": "ANY", 
      "value": ["<AD_LABEL_NAME>"] 
    } 
  ]' \
  -d 'time_range={"since":"2015-03-01","until":"2015-03-31"}' \
  -d 'fields=inline_link_clicks,cost_per_inline_link_click,total_actions' \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/act_<AD_ACCOUNT_ID>/insights

Filtering by ids using {object}.adlabel_ids on Insights edge:

use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdsInsightsFields;
use FacebookAds\Object\Values\AdsInsightsLevelValues;
use FacebookAds\Object\Values\InsightsOperators;
$account = new AdAccount('act_<AD_ACCOUNT_ID>');

$params = array(
  'level' => AdsInsightsLevelValues::AD,
  'filtering' => array(
    array(
      'field' => 'adgroup.adlabel_ids',
      'operator' => InsightsOperators::ANY,
      'value' => array(<AD_LABEL_ID>),
    ),
  ),
  'time_range' => array(
    'since' => '2015-03-01',
    'until' => '2015-03-31',
  ),
);

$fields = array(
  AdsInsightsFields::INLINE_LINK_CLICKS,
  AdsInsightsFields::COST_PER_INLINE_LINK_CLICK,
  AdsInsightsFields::TOTAL_ACTIONS,
);

$stats = $account->getInsights($fields, $params);
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.adsinsights import AdsInsights

ad_account = AdAccount('act_<AD_ACCOUNT_ID>')
params = {
    'fields': [
        AdsInsights.Field.unique_clicks,
        AdsInsights.Field.ctr,
        AdsInsights.Field.total_actions,
    ],
    'level': 'ad',
    'filtering': [
        {
            'field': 'adgroup.adlabel_ids',
            'operator': 'ANY',
            'value': ['<AD_LABEL_ID>'],
        },
    ],
    'time_range': {
        'since': '2015-03-01',
        'until': '2015-03-31',
    },
}
stats = ad_account.get_insights(params=params)
print(stats)
APINodeList<AdsInsights> adsInsightss = new AdAccount(act_<AD_ACCOUNT_ID>, context).getInsights()
  .setLevel(AdsInsights.EnumLevel.VALUE_AD)
  .setFiltering("[{\"field\":\"adgroup.adlabel_ids\",\"operator\":\"ANY\",\"value\":[\"" + <AD_LABEL_ID> + "\"]}]")
  .setTimeRange("{\"since\":\"2015-03-01\",\"until\":\"2015-03-31\"}")
  .requestField("inline_link_clicks")
  .requestField("cost_per_inline_link_click")
  .requestField("total_actions")
  .execute();
curl -G \
  -d 'level=ad' \
  --data-urlencode 'filtering=[ 
    { 
      "field": "adgroup.adlabel_ids", 
      "operator": "ANY", 
      "value": ["<AD_LABEL_ID>"] 
    } 
  ]' \
  -d 'time_range={"since":"2015-03-01","until":"2015-03-31"}' \
  -d 'fields=inline_link_clicks,cost_per_inline_link_click,total_actions' \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/act_<AD_ACCOUNT_ID>/insights

Similarly, field filtering can be used for finding ads, ad sets, campaigns just as done on the insights edge:

The filtering parameter is an array of filter object. Each filter object has three fields: 'field', 'operator' and 'value'. Valid filter operator could be ('EQUAL', 'NOT_EQUAL', 'GREATER_THAN', 'GREATER_THAN_OR_EQUAL', 'LESS_THAN', 'LESS_THAN_OR_EQUAL', 'IN_RANGE', 'NOT_IN_RANGE', 'CONTAIN', 'NOT_CONTAIN', 'IN', 'NOT_IN', 'ANY', 'ALL', 'NONE').

use FacebookAds\Object\AdAccount;

$account = new AdAccount('act_<AD_ACCOUNT_ID>');
$ads = $account->getAds(array(), array(
  'filtering' => array(
    array(
      'field' => 'adlabels',
      'operator' => 'ANY',
      'value' => array('for testing'),
    ),
  ),
));
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.ad import Ad

params = {
    'filtering': [
        {
            'field': 'adlabels',
            'operator': 'ANY',
            'value': ['for testing'],
        },
    ],
}

ad_account = AdAccount('act_<AD_ACCOUNT_ID>')
ads = ad_account.get_ads(fields=[Ad.Field.name], params=params)
APINodeList<Ad> ads = new AdAccount(act_<AD_ACCOUNT_ID>, context).getAds()
  .setParam("filtering", "[{\"field\":\"adlabels\",\"operator\":\"ANY\",\"value\":[\"for testing\"]}]")
  .execute();
curl -G \
  --data-urlencode 'filtering=[ 
    { 
      "field": "adlabels", 
      "operator": "ANY", 
      "value": ["for testing"] 
    } 
  ]' \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/act_<AD_ACCOUNT_ID>/ads

参数

这个端点不包含任何参数。

字段

字段描述
id
numeric string

Ad Label ID

created_time
datetime

Created time

name
string

Ad Label name

updated_time
datetime

Updated time

连线

连线描述
Edge<AdCreative>

Creatives associated with this label

Edge<Adgroup>

Ads associated with this label

Edge<AdCampaign>

Ad sets associated with this label

Edge<AdCampaignGroup>

Campaigns associated with this label

错误代码

错误描述
100Invalid parameter

创建

Examples

Creating Labels:

use FacebookAds\Object\AdLabel;
use FacebookAds\Object\Fields\AdLabelFields;

$label = new AdLabel(null, 'act_<AD_ACCOUNT_ID>');
$label->{AdLabelFields::NAME} = 'AdLabel name';
$label->create();
from facebookads.adobjects.adlabel import AdLabel

label = AdLabel(parent_id='act_<AD_ACCOUNT_ID>')
label[AdLabel.Field.name] = 'AdLabel name'
label.remote_create()
AdLabel adLabel = new AdAccount(act_<AD_ACCOUNT_ID>, context).createAdLabel()
  .setName("AdLabel name")
  .execute();
String ad_label_id = adLabel.getId();
curl \
  -F 'name=AdLabel name' \
  -F 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/act_<AD_ACCOUNT_ID>/adlabels

你可以通过下列路径向 adlabels 连线发出 POST 请求:
发布到这个连线会创建 an AdLabel

例子

Graph API Explorer
POST /v21.0/act_<AD_ACCOUNT_ID>/adlabels HTTP/1.1
Host: graph.facebook.com

name=My+Label+1
/* PHP SDK v5.0.0 */
/* make the API call */
try {
  // Returns a `Facebook\FacebookResponse` object
  $response = $fb->post(
    '/act_<AD_ACCOUNT_ID>/adlabels',
    array (
      'name' => 'My Label 1',
    ),
    '{access-token}'
  );
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();
/* handle the result */
/* make the API call */
FB.api(
    "/act_<AD_ACCOUNT_ID>/adlabels",
    "POST",
    {
        "name": "My Label 1"
    },
    function (response) {
      if (response && !response.error) {
        /* handle the result */
      }
    }
);
Bundle params = new Bundle();
params.putString("name", "My Label 1");
/* make the API call */
new GraphRequest(
    AccessToken.getCurrentAccessToken(),
    "/act_<AD_ACCOUNT_ID>/adlabels",
    params,
    HttpMethod.POST,
    new GraphRequest.Callback() {
        public void onCompleted(GraphResponse response) {
            /* handle the result */
        }
    }
).executeAsync();
NSDictionary *params = @{
  @"name": @"My Label 1",
};
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                               initWithGraphPath:@"/act_<AD_ACCOUNT_ID>/adlabels"
                                      parameters:params
                                      HTTPMethod:@"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                      id result,
                                      NSError *error) {
    // Handle the result
}];
curl -X POST \
  -F 'name="My Label 1"' \
  -F 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v21.0/act_<AD_ACCOUNT_ID>/adlabels
如果你希望详细了解如何使用图谱 API,请阅读我们的图谱 API 指南

参数

参数描述
name
string

AdLabel name

必填

返回类型

这个端点支持先写后读,并会读取返回类型中 id 代表的节点。
Struct {
id: numeric string,
}

错误代码

错误描述
100Invalid parameter
200Permissions error

更新

Examples

Renaming Labels: One can rename to a new name, only if a label with that name does not exist.

use FacebookAds\Object\AdLabel;
use FacebookAds\Object\Fields\AdLabelFields;

$label = new AdLabel(<AD_LABEL_ID>);
$label->{AdLabelFields::NAME} = 'New AdLabel name';
$label->read();
from facebookads.adobjects.adlabel import AdLabel

adlabel = AdLabel(<AD_LABEL_ID>)
adlabel[AdLabel.Field.name] = 'New AdLabel Name'
adlabel.remote_update()
AdLabel adLabel2 = new AdLabel(<AD_LABEL_ID>, context).get()
  .execute();
curl -G \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/<AD_LABEL_ID>

Associating with ad objects: One can use 'id' or 'name'. If a label with a given name exists, it will be re-used.

Associating an existing label with an existing ad object such as ads:

use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;
use FacebookAds\Object\Fields\AdLabelFields;

$ad = new Ad(<AD_ID>);
$ad->{AdFields::ADLABELS} = array(
  array(AdLabelFields::ID => <AD_LABEL_ID>),
  array(AdLabelFields::NAME => '<AD_LABEL_NAME>'),
);
$ad->update();
from facebookads.adobjects.ad import Ad
from facebookads.adobjects.adlabel import AdLabel

ad = Ad(<AD_ID>)
ad[Ad.Field.adlabels] = [
    {AdLabel.Field.id: <AD_LABEL_ID>},
    {AdLabel.Field.name: '<AD_LABEL_NAME>'},
]
ad.remote_update()
new Ad(<AD_ID>, context).update()
  .setAdlabels("[{\"id\":\"" + <AD_LABEL_ID> + "\"},{\"name\":\"" + <AD_LABEL_NAME> + "\"}]")
  .execute();
curl \
  -F 'adlabels=[{"id":"<AD_LABEL_ID>"},{"name":"<AD_LABEL_NAME>"}]' \
  -F 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/<AD_ID>

This endpoint overrides all set of labels associated with this object, whereas <OBJECT_ID>/adlabels modifies (adds new or reuses specified). If only the label name is supplied, and a label with the name does not exist, then a new label is created and then associated with the ad object.

Adding new associations to existing ad object such as ads using label id

use FacebookAds\Object\Ad;

$ad = new Ad(<AD_ID>);
$ad->createAdLabel(array(), array('adlabels' => array(<AD_LABEL_ID>)));
from facebookads.adobjects.ad import Ad

ad = Ad(ad_id)
adlabels = [<AD_LABEL_ID>]
ad.add_labels(adlabels)
AdLabel adLabel2 = new Ad(<AD_ID>, context).createAdLabel()
  .setAdlabels("[{\"id\":\"" + <AD_LABEL_ID> + "\"}]")
  .execute();
curl \
  -F 'adlabels=["<AD_LABEL_ID>"]' \
  -F 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/<AD_ID>/adlabels

你可以向 /{ad_label_id} 发出 POST 请求,以更新 an AdLabel

参数

参数描述
name
string

AdLabel name

必填

返回类型

这个端点支持先写后读,并会读取接收你的 POST 请求的节点。
Struct {
success: bool,
}

错误代码

错误描述
100Invalid parameter
你可以向 /{ad_creative_id}/adlabels 发出 POST 请求,以更新 an AdLabel

参数

参数描述
adlabels
list<Object>

Specification of ad labels to be associated with the creative

必填

返回类型

这个端点支持先写后读,并会读取接收你的 POST 请求的节点。
Struct {
success: bool,
}

错误代码

错误描述
100Invalid parameter
你可以向 /{ad_id}/adlabels 发出 POST 请求,以更新 an AdLabel

参数

参数描述
adlabels
list<Object>

Specification of adlabels to be associated with the ad

必填
execution_options
list<enum{validate_only}>
默认值:Set

An execution setting
validate_only: when this option is specified, the API call will not perform the mutation but will run through the validation rules against values of each field.
If the call passes validation or review, response will be {"success": true}. If the call does not pass, an error will be returned with more details. These options can be used to improve any UI to display errors to the user much sooner, e.g. as soon as a new value is typed into any field corresponding to this ad object, rather than at the upload/save stage, or after review.

返回类型

这个端点支持先写后读,并会读取接收你的 POST 请求的节点。
Struct {
success: bool,
}

错误代码

错误描述
100Invalid parameter
你可以向 /{campaign_id}/adlabels 发出 POST 请求,以更新 an AdLabel

参数

参数描述
adlabels
list<Object>

Specification of ad labels to be associated with the campaign

必填
execution_options
list<enum{validate_only}>
默认值:Set

An execution setting
validate_only: when this option is specified, the API call will not perform the mutation but will run through the validation rules against values of each field.
If the call passes validation or review, response will be {"success": true}. If the call does not pass, an error will be returned with more details. These options can be used to improve any UI to display errors to the user much sooner, e.g. as soon as a new value is typed into any field corresponding to this ad object, rather than at the upload/save stage, or after review.

返回类型

这个端点支持先写后读,并会读取接收你的 POST 请求的节点。
Struct {
success: bool,
}

错误代码

错误描述
100Invalid parameter

删除

Examples

Deleting Labels:

use FacebookAds\Object\AdLabel;

$label = new AdLabel(<AD_LABEL_ID>);
$label->deleteSelf();
from facebookads.adobjects.adlabel import AdLabel

adlabel = AdLabel(<AD_LABEL_ID>)
adlabel.remote_delete()
new AdLabel(<AD_LABEL_ID>, context).delete()
  .execute();
curl -X DELETE \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/<AD_LABEL_ID>/

Removing Existing Associations from an ad object:

use FacebookAds\Object\Ad;

$campaign = new Ad(<AD_ID>);
$campaign->deleteAdLabels(array(), array('adlabels' => array(<AD_LABEL_ID>)));
from facebookads.adobjects.ad import Ad

ad = Ad(<AD_ID>)
adlabels = [<AD_LABEL_ID>]
ad.remove_labels(adlabels)
new Ad(<AD_ID>, context).deleteAdLabels()
  .setAdlabels("[{\"id\":\"" + <AD_LABEL_ID> + "\"}]")
  .execute();
curl -X DELETE \
  -d 'adlabels=["<AD_LABEL_ID>"]' \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/<AD_ID>/adlabels

你可以向 /{ad_label_id} 发出“删除”请求来删除 an AdLabel

参数

这个端点不包含任何参数。

返回类型

Struct {
success: bool,
}

错误代码

错误描述
100Invalid parameter