skip to Main Content

So im trying to fetch the ads and their respective images from the Facebook API. So far i manage to get the Ads and now im trying to get the creative for that ad but im failing with every try.

FacebookAdsApi.init(access_token=access_token)

fields = [
    'ad_id',
    'ad_name',
    'impressions',
    'clicks',
    'spend',
    'campaign_name',
    'reach',
    'relevance_score'
]
params = {
    'time_range': {'since': date,'until': date},
    'filtering': [],
    'level': 'ad',
    'breakdowns': [],
}
data = AdAccount(ad_account_id).get_insights(
    fields=fields,
    params=params,
)

creativeFields = [
    'image_url',
    'link_url',
    'preview_url',
    'template_url'
]

vecData = []
for n in data:
    ad = Ad(str(n._data[str('ad_id')]))
    creatives = ad.get_ad_creatives(fields=creativeFields)
    print(creatives)

Any idea on how can i get the image url for the creative of a specific ad?

2

Answers


  1. Chosen as BEST ANSWER

    My solution is not the best but it works!

    creativeFields = [
        'thumbnail_url',
    ]
    
    
    vecData = []
    for n in data:
        ad = Ad(str(n._data[str('ad_id')]))
        creatives = ad.get_ad_creatives(fields=creativeFields)
        parsed = urlparse.urlparse(creatives[0][AdCreative.Field.thumbnail_url])
        img = urlparse.parse_qs(parsed.query)['url'][0].replace('u'','').replace(''','')
    

    Basically i discover i was able to retrieve the url for the thumbnail image and this url had as parameter 'url' the original picture so i took it from there.

    Hope it helps!


  2. In order to retrieve the url for the image you first have to obtain the image hash from the Ad Creative object story spec.

    Request the object story spec when request the ad creative:

    creativeFields = [
    'image_url',
    'link_url',
    'preview_url',
    'template_url',
    'object_story_spec'
    ]
    

    Extract the desired image_hash from the object story spec. The example below will work for an ad with one image.

    imageHash = creatives[0]['object_story_spec']['link_data']
    

    Then request the permanent url for the image hash from the ad account.

    fields = ['id','permalink_url','name']
    params = {'hashes':[imageHash]}
    imageHashes = AdAccount(ad_account_id).getAdImages(
    fields=fields,
    params=params,
    )
    print(imageHashes)
    

    I’m not able to test the code above but it should get you the image.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search