With python I’m using Insights API in order to get data (at the campaign level) of the facebook business manager report (impressions, clicks etc etc).
I’m using the following code:
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
access_token = "****"
app_secret = "****"
app_id = "*****"
ad_accounts = [{"name": "***", "id": "act_****"}, {"name": "***", "id": "act_****"}]
fields = [
'reach',
'impressions',
'spend',
'clicks',
'account_id',
'account_name',
'campaign_name',
'campaign_id',
'date_start',
'date_stop',
'objective',
'inline_link_clicks',
'inline_post_engagement',
'inline_link_click_ctr',
'actions',
'estimated_ad_recallers'
]
params = {
# since not less than 37 months ago
'time_range': {'since':'2018-07-05', 'until':'2021-08-02'},
'filtering': [],
'level': 'campaign',
'breakdowns': [],
'limit': 100000,
'use_unified_attribution_setting': True
}
for ad_account in ad_accounts:
report_campaigns = list(AdAccount(ad_account['id']).get_insights(
fields=fields,
params=params,
)
)
My problem is that i need the “Results” field too. Although it is available in the fb business manager UI (see image below), “Results” is not available among all the possible fields of the insight API.
I wonder if there is a way to have the Results metric via API.
I know I could compute this field knowing the objective of the campaign, however I have many custom objectives so this approach would be very long and I would like to avoid it if possible.
Looks to me like what you're looking for is provided under the "conversion_values" field which in turn has action_type as one of its parameters: https://developers.facebook.com/docs/marketing-api/reference/ads-action-stats/
It helps to remember that the names you see in the UI don't have to match the names coming from the API. Reading documentations may not be sexy, but given the proper attention they deserve, they almost never disappoint you.
Related
Campaign Monitor is a service where we can send emails to a set of subscribers. We can create multiple lists within Campaign Monitor and add the required users to these lists as subscribers(to whom we can send personalised emails). So, here I am trying to send a set of customers' details like their name, emails, total_bookings, and first_booking to the campaign monitor's list using the API in Python so that I can send emails to this set of users.
More details on campaign monitor: https://www.campaignmonitor.com/api/v3-3/subscribers/
I am new to using Campaign Monitor. I have searched documentation, a lot of posts and blogs for examples on how to push data with multiple custom fields to Campaign Monitor using Python. By default, a list in Campaign Monitor will have a name and an email that can be added, but I want to add other details for each subscriber(here I want to add total_bookings and first_booking data) and Campaign Monitor provides custom fields to achieve this.
For instance:
I have my data stored in a redshift table named customer_details with the fields name, email, total_bookings, first_booking. I was able to retrieve this data from redshift table using Python with the following code.
# Get the data from the above table:
cursor = connection.cursor()
cursor.execute("select * from customer_details")
creator_details = cursor.fetchall()
# Now I have the data as a list of sets in creator_details
Now I want to push this data to a list in the Campaign Monitor using API like request.put('https://api.createsend.com/api/../.../..'). But I am not sure on how to do this. Can someone please help me here.
400 indicated invalid parameters
we can first see the request is POST not PUT
so first change requests.put to requests.post
the next thing is that all the variables need to be sent either as www-formdata or as json body data not sure which
and lastly you almost certainly cannot verify with basic auth ... but maybe
something like the following
some_variables = some_values
...
header = {"Authorization": f"Bearer {MY_API_KEY}"}
data = {"email":customer_email,"CustomFields":[{"key":"total_bookings","value":customer_details2}]}
url = f'https://api.createsend.com/api/v3.3/subscribers/{my_list_id}.json'
res = requests.post(url,json=data,headers=header)
print(res.status_code)
try:
print(res.json())
except:
print(res.content)
after looking more into the API docs it looks like this is the expected request
{
"EmailAddress": "subscriber#example.com",
"Name": "New Subscriber",
"MobileNumber": "+5012398752",
"CustomFields": [
{
"Key": "website",
"Value": "http://example.com"
},
{
"Key": "interests",
"Value": "magic"
},
{
"Key": "interests",
"Value": "romantic walks"
}
],
"Resubscribe": true,
"RestartSubscriptionBasedAutoresponders": true,
"ConsentToTrack":"Yes"
}
which we can see has "EmailAddress" not "email" so you would need to do
data = {"EmailAddress":customer_email,"CustomFields":[{"key":"total_bookings","value":customer_details2}]}
Im not sure if all of the fields are required or not ... so you may also need to provide "Name","MobileNumber",Resubscribe",etc
and looking at "Getting Started" it looks like the publish a python package to make interfacing simpler
http://campaignmonitor.github.io/createsend-python/
which makes it as easy as
import createsend
cli = createsend.CreateSend({"api_key":MY_API_KEY})
cli.subscriber.add(list_id,"user#email.com","John Doe",custom_fields,True,"No")
(which I found here https://github.com/campaignmonitor/createsend-python/blob/master/test/test_subscriber.py#L70)
I find difficulty on how to pass attributes to a product using the woocommerce rest api.
I successfully took the attribute id.
my function:
def assign_attribute_to_products(wcapi_yachtcharterapp,post_id,attribute_id):
#the post_id argument is the product id
data = {
"attributes": [
{
"id": attribute_id,
},
],
}
wcapi_yachtcharterapp.put("products/"+str(post_id), data).json()
The product is updated without passing the information of attribute_id.
Any idea how to fix this?
You are missing some data, take a look here
This works for me:
data = {'attributes': [{'id': 7,
'options': ['term01', 'term02'],
'variation': 'true',
'visible': 'true'}]}
even though the data type for visible and variation is a boolean in the docs, you have to set 'true' or 'false' with a string.
You have to include the options for variations.
Hope this helps.
I'm using the python Facebook API's SDK.
I am currently able to request and obtain campaign insights from the account level, with a snippet as such:
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adsinsights import AdsInsights as Insights
account = AdAccount(u"act_{}".format(account_id))
report_params = {
'time_increment': time_increment,
'time_range': {
'since': start_date.strftime("%Y-%m-%d"),
'until': end_date.strftime("%Y-%m-%d"),
},
'level': 'campaign'
}
insights = account.get_insights(fields=['campaign_name', 'spend'],
params=report_params, pending=True).execute()
The problem is that I can't seem to get information about a deleted campaign, that was active for a time, meaning that it has a spend value.
Here I read that adding a filtering might give me also DELETED or ARCHIVED campaigns, but in the get_insights documentation page I can't seem to find a field to filter on, and every try has been unsuccessful
I found the right filter, even though the effective_status is not obtainable through insight fields, you can use it in filters, in my case I included every possible campaign.effective_status. Using the following report_params
report_params = {
'time_increment': time_increment,
'time_range': {
'since': start_date.strftime("%Y-%m-%d"),
'until': end_date.strftime("%Y-%m-%d"),
},
'level': 'campaign',
'filtering': [{'field': 'campaign.effective_status',
'operator': 'IN',
'value': ['ACTIVE', 'PAUSED', 'DELETED', 'PENDING_REVIEW', 'DISAPPROVED',
'PREAPPROVED', 'PENDING_BILLING_INFO', 'CAMPAIGN_PAUSED', 'ARCHIVED',
'ADSET_PAUSED']}]
}
I have simple question regarding the Magento V1 media API. I'm trying to add a video to a product but it keeps telling me that is missing values.
I'm trying to add the data from Odoo (python) like this:
videoFile = {
"entry": {
'position': position,
'media_type': 'external-video',
'disabled': False,
'label': 'Holassss',
'types': ['image', 'small-image', 'thumbnail'],
'content': {
'base64_encoded_data': base64.b64encode(urllib.request.urlopen("https://img.youtube.com/vi/axwE9q7llEQ/0.jpg").read()).decode('ascii'),
'type': 'image/jpeg',
'name': '0.jpg'
},
'extension_attributes': {
'video_content': {
'media_type': 'external-video',
'video_provider': 'youtube',
'video_url': 'https://www.youtube.com/watch?v=axwE9q7llEQ',
'video_title': 'Titulo',
'video_description': 'Description',
'video_metadata': None,
}
}
}
}
cc = json.dumps(videoFile)
productUrl = url + "/index.php/rest/V1/products/" + productSku + "/media"
Eventually I'll add the content using the https://www.youtube.com/oembed?url=youtubeurl&format=json response.
I'm following the API documentation (http://devdocs.magento.com/swagger/index_20.html) for
catalogProductAttributeMediaGalleryManagementV1 (/V1/products/{sku}/media)
Error:
"message": "Option values that are not specified."
Please advice me on which values I'm missing and which I can leave NULL. Also let me know if there is a way to let Magento automatically get the description and other data (as on the admin panel) instead of providing it myself. last but not least, I think this documentation is missing some data. This already happened to me before with a different call and a couple of "optional" values were actually required. Is there another documentation web page?
Thank you very much.
I want to test it on the side of the functionality of the subscription payment gateway Braintree - for my application using Django (python).
Your code I have only one py file. (without front-end). When I want to create a subscription I get an error:
<ErrorResult 'Payment method token is invalid.' at 7f101d301390>
How can I get token payment method?
Here is all my code:
import braintree
braintree.Configuration.configure(braintree.Environment.Sandbox,
merchant_id="myMechrantId",
public_key="myPublicKey",
private_key="myPrivateKey")
client_token = braintree.ClientToken.generate()
client = braintree.Customer.create({
"first_name": 'Mike',
"last_name": "Smith",
"company": "Braintree",
"email": "jen#example.com",
"phone": "312.555.1234",
"fax": "614.555.5678",
"website": "www.example.com"
})
result = braintree.Subscription.create({
"payment_method_token": "the_token",
"plan_id": "Here is my plan ID"
})
I work at Braintree. Please get in touch with our support team if you have more questions.
In general, one of the main benefits of a service like Braintree is that you never have to handle credit card numbers, so you're better off following the Braintree recurring billing guide instead, which will better match a real integration with Braintree.
That said, if you do want to test it without a front-end, you can test it like this:
result = braintree.Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "12/16"
}
})
result = braintree.Subscription.create({
"payment_method_token": result.customer.credit_cards[0].token,
"plan_id": "my_plan_id"
})
It's late but I got stuck on this problem recently, this is the solution that helped me
customer_create_result = gateway.customer.create({
"first_name": user.first_name,
"last_name": user.middle_name + '' + user.last_name,
"payment_method_nonce": payment_method_nonce
})
subscription_create_result = gateway.subscription.create({
"payment_method_token":
customer_create_result.customer.payment_methods[0].token,
"plan_id": braintree_plan_id
})
where payment_method_nonce can be obtained from payload.nonce on payment button click and braintree_plan_id is the id for the plan you create in braintree control panel
here is the braintree reference that helped me
https://developer.paypal.com/braintree/docs/guides/customers#create-with-payment-method