Facebook Marketing API: Potential reach of a Facebook campaign - python

We can run Facebook advert using python SDK. I want to know the potential reach of target audience. Is there any command available or any other way?

To get the Reach Estimates of a targeting specification using ad account.
account = AdAccount('act_<AD_ACCOUNT_ID>')
targeting_spec = {
'geo_locations': {
'countries': ['US'],
},
'age_min': 20,
'age_max': 40,
}
params = {
'currency': 'USD',
'optimize_for': AdSet.OptimizationGoal.offsite_conversions,
'targeting_spec': targeting_spec,
}
reach_estimate = account.get_reach_estimate(params=params)
print(reach_estimate)
Response Result
{
"data": {
"users": 186000000,
"bid_estimations": [
{
"unsupported": false,
"location": 3,
"bid_amount_min": 39,
"bid_amount_median": 80,
"bid_amount_max": 121
}
],
"estimate_ready": true
}
}
186000000 users base on mention criteria
Ad Account Reachestimate

Related

How to get parameter values out of json post

I am trying to use the bing maps api to get travel time and distance between 2 gps coordinates.
I get a json answer, however, I am not able to get the values out of this dictionary ?
import requests
import json
payload = {
"origins": [{"latitude": 50.781869, "longitude": 4.596188}],
"destinations": [{"latitude": 50.87650130092019, "longitude": 4.671327819416231}],
"travelMode": "driving",
}
paramtr = {"key": "mybingAPIkey"}
r = requests.post('https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix', data = json.dumps(payload), params = paramtr)
print(r.json())
gives the following result:
{
'authenticationResultCode': 'ValidCredentials',
'brandLogoUri': 'http: //dev.virtualearth.net/Branding/logo_powered_by.png',
'copyright': 'Copyright © 2023 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.',
'resourceSets': [
{
'estimatedTotal': 1,
'resources': [
{
'__type': 'DistanceMatrix:http://schemas.microsoft.com/search/local/ws/rest/v1',
'destinations': [
{
'latitude': 50.87650130092019,
'longitude': 4.671327819416231
}
],
'origins': [
{
'latitude': 50.781869,
'longitude': 4.596188
}
],
'results': [
{
'destinationIndex': 0,
'originIndex': 0,
'totalWalkDuration': 0,
'travelDistance': 14.511,
'travelDuration': 21.9667
}
]
}
]
}
],
'statusCode': 200,
'statusDescription': 'OK',
'traceId': '7fecad5b38b94df9acef6287488b68c9|DU0000273D|0.0.0.0|DU000005E8'
}
now: how do I get the travelDistance out of this ? (14.511 in this case)
or the travelDuration ? (21.9667)
tried to get the key and value pairs, but not really getting further with this.
with some other code, I got the keys :
authenticationResultCode
brandLogoUri
copyright
resourceSets
statusCode
statusDescription
traceId
You could also use json.loads() and pass the content of your response. Then access values like you do from a dictionary:
r = requests.post('https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix', data = json.dumps(payload), params = paramtr)
dt = json.loads(r.content)
travelDistance = dt['resourceSets'][0]['resources'][0]['results'][0]['travelDistance']
travelDuration = dt['resourceSets'][0]['resources'][0]['results'][0]['travelDuration']

How to use conditionals on Uniswap GraphQL API pool method?

So I'm new to graphQL and I've been figuring out the Uniswap API, through the sandbox browser, but I'm running this program which just gets metadata on the top 100 tokens and their relative pools, but the pool one isn't working at all. I'm trying to put two conditions of if token0's hash is this and token1's hash is this, it should output the pool of those two, however if only outputs pools with the token0 hash, and just ignores the second one. I've tried using and, _and, or two where's seperated by {} or , so on so forth. This is an example I have (python btw):
class ExchangePools:
def QueryPoolDB(self, hash1, hash2):
query = """
{
pools(where: {token0: "%s"}, where: {token1:"%s"}, first: 1, orderBy:volumeUSD, orderDirection:desc) {
id
token0 {
id
symbol
}
token1 {
id
symbol
}
token1Price
}
}""" % (hash1, hash2)
return query
or in the sandbox explorer this:
{
pools(where: {token0: "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"} and: {token1:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"}, first: 1, orderBy:volumeUSD, orderDirection:desc) {
id
token0 {
id
symbol
}
token1 {
id
symbol
}
token1Price
}
}
with this output:
{
"data": {
"pools": [
{
"id": "0x4585fe77225b41b697c938b018e2ac67ac5a20c0",
"token0": {
"id": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",
"symbol": "WBTC"
},
"token1": {
"id": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
"symbol": "WETH"
},
"token1Price": "14.8094450357546760737720184457113"
}
]
}
}
How can I get the API to register both statements?

Is it possible to retreive object_story_spec for an ad creative which was not created with that object_story_spec? [Python Facebook API]

I have a set of ad creatives that I retreive through the Facebook Business Python SDK. I need these specifically to retreive the outbound URL when someone clicks on the ad: AdCreative['object_story_spec']['video_data']['call_to_action']['value']['link'].
I use the following call:
adcreatives = set.get_ad_creatives(fields=[
AdCreative.Field.id,
AdCreative.Field.name,
AdCreative.Field.object_story_spec,
AdCreative.Field.effective_object_story_id ,
])
Where set is an ad set.
For some cases, the result looks like this (with actual data removed), which is expected:
<AdCreative> {
"body": "[<BODY>]",
"effective_object_story_id": "[<EFFECTIVE_OBJECT_STORY_ID>]",
"id": "[<ID>]",
"name": "[<NAME>]",
"object_story_spec": {
"instagram_actor_id": "[<INSTAGRAM_ACTOR_ID>]",
"page_id": "[<PAGE_ID>]",
"video_data": {
"call_to_action": {
"type": "[<TYPE>]",
"value": {
"link": "[<LINK>]", <== This is what I need
"link_format": "[<LINK_FORMAT>]"
}
},
"image_hash": "[<IMAGE_HASH>]",
"image_url": "[<IMAGE_URL>]",
"message": "[<MESSAGE>]",
"video_id": "[<VIDEO_ID>]"
}
}
}
While sometimes results look like this:
<AdCreative> {
"effective_object_story_id": "[<EFFECTIVE_OBJECT_STORY_ID>]",
"id": "[<ID>]",
"name": "[<NAME>]",
"object_story_spec": {
"instagram_actor_id": "[<INSTAGRAM_ACTOR_ID>]",
"page_id": "[<PAGE_ID>]"
}
}
According to this earlier question: Can't get AdCreative ObjectStorySpec this is due to the fact that the object_story_spec is not populated if it is linked to a creative, instead of created along with the creative.
However, the video_data (and as such, the link), should be saved somewhere. Is there a way to retreive this? Maybe through effective_object_story_id?
The documentation page for object_story_spec (https://developers.facebook.com/docs/marketing-api/reference/ad-creative-object-story-spec/v12.0) does not have the information I am looking for.

Add a Protected Range to an existing NamedRange

I have an existing worksheet with an existing NamedRange for it and I would like to call the batch_update method of the API to protect that range from being edited by anyone other than the user that makes the batch_update call.
I have seen an example on how to add protected ranges via a new range definition, but not from an existing NamedRange.
I know I need to send the addProtectedRangeResponse request. Can I define the request body with a Sheetname!NamedRange notation?
this_range = worksheet_name + "!" + nrange
batch_update_spreadsheet_request_body = {
'requests': [
{
"addProtectedRange": {
"protectedRange": {
"range": {
"name": this_range,
},
"description": "Protecting xyz",
"warningOnly": False
}
}
}
],
}
EDIT: Given #Tanaike feedback, I adapted the call to something like:
body = {
"requests": [
{
"addProtectedRange": {
"protectedRange": {
"namedRangeId": namedRangeId,
"description": "Protecting via gsheets_manager",
"warningOnly": False,
"requestingUserCanEdit": False
}
}
}
]
}
res2 = service.spreadsheets().batchUpdate(spreadsheetId=ssId, body=body).execute()
print(res2)
But although it lists the new protections, it still lists 5 different users (all of them) as editors. If I try to manually edit the protection added by my gsheets_manager script, it complains that the range is invalid:
Interestingly, it seems to ignore the requestUserCanEdit flag according to the returning message:
{u'spreadsheetId': u'NNNNNNNNNNNNNNNNNNNNNNNNNNNN', u'replies': [{u'addProtectedRange': {u'protectedRange': {u'requestingUserCanEdit': True, u'description': u'Protecting via gsheets_manager', u'namedRangeId': u'1793914032', u'editors': {}, u'protectedRangeId': 2012740267, u'range': {u'endColumnIndex': 1, u'sheetId': 1196959832, u'startColumnIndex': 0}}}}]}
Any ideas?
How about using namedRangeId for your situation? The flow of the sample script is as follows.
Retrieve namedRangeId using spreadsheets().get of Sheets API.
Set a protected range using namedRangeId using spreadsheets().batchUpdate of Sheets API.
Sample script:
nrange = "### name ###"
ssId = "### spreadsheetId ###"
res1 = service.spreadsheets().get(spreadsheetId=ssId, fields="namedRanges").execute()
namedRangeId = ""
for e in res1['namedRanges']:
if e['name'] == nrange:
namedRangeId = e['namedRangeId']
break
body = {
"requests": [
{
"addProtectedRange": {
"protectedRange": {
"namedRangeId": namedRangeId,
"description": "Protecting xyz",
"warningOnly": False
}
}
}
]
}
res2 = service.spreadsheets().batchUpdate(spreadsheetId=ssId, body=body).execute()
print(res2)
Note:
This script supposes that Sheets API can be used for your environment.
This is a simple sample script. So please modify it to your situation.
References:
ProtectedRange
Named and Protected Ranges
If this was not what you want, I'm sorry.
Edit:
In my above answer, I modified your script using your settings. If you want to protect the named range, please modify body as follows.
Modified body
body = {
"requests": [
{
"addProtectedRange": {
"protectedRange": {
"namedRangeId": namedRangeId,
"description": "Protecting xyz",
"warningOnly": False,
"editors": {"users": ["### your email address ###"]}, # Added
}
}
}
]
}
By this, the named range can be modified by only you. I'm using such settings and I confirm that it works in my environment. But if in your situation, this didn't work, I'm sorry.

Iterating json response from google api using python

I took a nearby location from google api and i get json, when i try to split json i receive error
{
u'status':u'OK',
u'next_page_token':u'CoQC9AAAAHepdLFIvAUuqz6y6WWasKBmq5aAOYr0Bbu97upCMy4EI1Ea5t-6S6iObZdZ5_RIB7ywocdG-lF9ian5JRuTQVGL7MwbBa_uN3EfS7XzjmlVx-IKsauiEiO-Wu3r25zk9SL3yc5d_vDGvN3VQJkA7bBiDWhkloJ4RFngjBsGVWVQOnj5glrbwVVrw9Nu6DNi70C2Wdqqy_65b_jFjJiJYTAwrlfoyl7GGpxk5Gng7QgSFdtTJII9zdfkxcj3osUzklRetjraDtgfaQgxr0KA_H5btbuXz3UT6r-dyqdj2qd1tr_0oAvFkGB9t0qFbUYSe7bDETEAwdDv7MSmmXeYHQUSEMCBruHU5pb8X4EoPbPw9ncaFLgqTTICkQyGYY-boaJ1_3X3SaeT',
u'html_attributions':[
u'Listings by Indiacom Yellow Pages'],
u'results':[
{
u'name':u'Institute for Financial Management and Research',
u'reference':u'CpQBgwAAAL5Gg4T18LzUpNTEzvKWeAH0jLBuTyC_rmxOycL3KndgQ05WVKovVhiIYhnnqeOxcX1tcWesIi0vSVwugaskyy2UnJ_BrTD5ZblXzD7nLxP9L-FOQLetRgbpA6DlNzHM6Nmcu3jtJiBAOyMQJOmgL9cot7c4y18o_3E1cJrzPJfg5hK6trq2u2lvJnD2ZxJ6IxIQC2IuHwQILkrbtUd3ke5GDBoU1sZLoPY-_kARc7lEoq2naKHtwSk',
u'geometry':{
u'location':{
u'lat':13.062882,
u'lng':80.238669
}
},
u'place_id':u'ChIJKzE7o2ZmUjoRLaCtNPjba3U',
u'vicinity':u'24,
Kothari Road,
Nungambakkam,
Chennai',
u'photos':[
{
u'photo_reference':u'CnRoAAAApH-YJpJFjPYltZYhYTs_tIVFA7vve-LMii8XbUydZJLMXbzDNkxuCuGCk9W-nFjgUrj-JoRqJLRuurGvt1oz94osENNc8bZGLBI4Joj1w-dQSyiwqqzqDdna-u0TRkJ_8S91fF3uerww341951YB2hIQX7gFjIn5tWkkEcGwErJ9oBoU0CdKRd6b2pL3Bcp09hCYvleEfaQ',
u'width':816,
u'html_attributions':[
u'From a Google User'
],
u'height':459
}
],
u'scope':u'GOOGLE',
u'id':u'2e9a63cf7368e0f90e2a20711ac56853b7c34462',
u'types':[
u'school',
u'establishment'
],
u'icon': u'http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png'
},
{
u'rating':4.2,
u'name':u'Sri Sankara Senior Secondary School',
u'reference':u'CoQBdgAAAJ-Uc78EbPnLX6adzheZMWrS9sOJ9vWTQsqZOlQza-r3qozDUrl4XxWPRdHD9K_BVP0t_FhEwQt4w42X0z01uQr7dtq5cZ7ioa9zBVIQpwOkSQhxjbjQjX05YxVqGPB9MCfEikHpFKSKIaz5mPrLDgklbhQ8clD4fm9BiWNmE_mJEhD35R4GgbVNu4J-x0Lfaw3BGhRPQEXErZf3jJJkLbHs2HWVRvP2Xg',
u'geometry':{
u'location':{
u'lat':13.009931,
u'lng':80.260746
}
},
u'place_id':u'ChIJh_fXcelnUjoRd4vKDQfY_DM',
u'vicinity':u'9/21 Vasantha Press Road,
Vasanta Press Road,
Adyar,
Landmarks are Malar Hospital/Theosophical society,
Chennai',
u'photos':[
{
u'photo_reference':u'CnRwAAAAIrFQSUJn7JB5_GgDfEPBldHptKmARqhV-6HR5fUT-MjB6ScO7ZYz1jamqoGvTqXlbEZZjxC67BvOllBHTiRIQwKyBXoI9DhleBmrCgMTrorjeDkvIDY_8ZC0pOFZOZGGH2XdfLrH1irsWZUEa0IjFRIQaATxA2BymP1KED4vxNZfnxoUTwD5Y-4-8ZPnPrhuKofUVSztcoQ',
u'width':297,
u'html_attributions':[
],
u'height':297
}
],
u'scope':u'GOOGLE',
u'id':u'a8dc412bac3ea790260d2c7d6fe08271ae883a4e',
u'types':[
u'school',
u'establishment'
],
u'icon': u'http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png'
},
{
u'rating':4.5,
u'name':u'Chettinad Vidyashram',
u'reference':u'CnRoAAAAbIG1-6ecTuOcqw5hCenhtbHlAmP-nfdw_W1vEv94fXvIyCzhHSQMn95VEtKCgbLeME6qd30uGhxmLxFwXItcls-SlC7fgXwGl2JINCLTjB1RYpYC--Gr6hS-9cT7Xq2f46-dAqnpF5n2sRa1cNJJSBIQvVLDztqmh2BmqkJER9MLZxoU3gbS1TpgVj8h5Uo71QKTTyj1CdQ',
u'geometry':{
u'location':{
u'lat':13.017083,
u'lng':80.269503
}
},
u'place_id':u'ChIJR3w9SdxnUjoRs2vfnH-ERNA',
u'vicinity':u'Rajah Annamalaipuram,
Chennai',
u'photos':[
{
u'photo_reference':u'CnRoAAAAeUHwPDKO87eeGP7Fzm7aKE3VcQd6gFebbjo2FhYRHdulLZW-XdepstzETly74Id6NMOF5lqm4BHZ56C1CRnsxmdqaxJ-rcJR2Cpq2VfJaixZmBG3C-0TTNmMuPuGsjKAldr6rWCWdDVMg8FAnWhgyRIQXYPX89XdA5fl7e5RUecRWhoU-SExDqUr-GRaYVLkb8Iq_1mf-R8',
u'width':968,
u'html_attributions':[
u'From a Google User'
],
u'height':968
}
],
u'scope':u'GOOGLE',
u'id':u'f3b774d4c11a4bd20585669d9c4ae57fc12e5652',
u'types':[
u'school',
u'establishment'
],
u'icon': u'http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png'
},
Here is my python code
res = json.dumps(response)
for result in response[status][results]:
print result['status']
as json was big i put half json data only.
Error i get is ror at 1431:global name 'status' is not defined
How to split this json
When i print type(response)
type tuple
If you get a json string you want to load it into the native structure with loads and then iterate over that native structure. Looking at the json string you have it also seems as if the individual results don't have a status field. You could do something like this:
res = json.loads(response)
print res['status']
for result in res['results']:
print result

Categories

Resources