How to get insights on Facebook Business API using Python? - python

I have this code below with my credentials;
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.campaign import Campaign
my_app_id = ''
my_app_secret = ''
my_access_token = ''
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
my_account = AdAccount('')
my_campaign = Campaign('')
When I run the code below, I get an error.
Input:
my_account_insights = my_account.get_insights()
print(my_account_insights)
Output:
FacebookRequestError:
Message: Call was not successful
Method: GET
Path: https://graph.facebook.com/v12.0/act_2193000197632450/adsets
Params: {'summary': 'true'}
Status: 400
Response:
{
"error": {
"message": "(#100) Missing permissions",
"type": "OAuthException",
"code": 100,
"fbtrace_id": "AvMDtZu8KYqYG8qt3repNjL"
}
}
What am I missing? Could you please help me to figure it out?

Generate a new token https://developers.facebook.com/tools/explorer/ and set the permission accordingly

Related

How to replace all users in a Custom Audience using the Facebook Marketing API

I'm trying to work out how to replace the users in a Custom Audience. I'm able to delete and create a new audience, but ideally I just want to update the existing audience as it's shared with other accounts.
I think I may be able to do this using create_users_replace but Im getting the error message:
facebook_business.exceptions.FacebookRequestError:
Message: Call was not successful
Method: POST
Path: https://graph.facebook.com/v13.0/23850060704540982/usersreplace
Params: {}
Status: 400
Response:
{
"error": {
"message": "(#100) The parameter session is required",
"type": "OAuthException",
"code": 100,
"fbtrace_id": "AOJ9p0Hd1Kla4NRlkhOnHIQ"
}
}
Here's the code I'm trying to use:
from collections import UserList
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.customaudience import CustomAudience
from facebook_business.api import FacebookAdsApi
test_id = '2385040704549815'
api = FacebookAdsApi.init(access_token=access_token)
session_id = '123456789'
session = {
'session_id':session_id,
'batch_seq': 1,
'last_batch_flag':False,
}
# List of hashed email addresses (SHA256)
test_audience_list = ["8b84db83027ecd2764ac56dd6ed62aa761ea315e0268c64e34104a6536f"]
# I can add a list of users to a custom audience using this
CustomAudience(test_id).add_users(schema="EMAIL_SHA256", users=test_audience_list)
# I'm unable to replace all users with a new list
CustomAudience(test_id).create_users_replace(fields=None, params=None, batch=None)
I've also tried including the session parameter:
CustomAudience(test_id).create_users_replace(fields=None, params=None, batch=None, success=None, failure=None, session=session)
but then I get an error about an unexpected keyword argument 'session'.
Is it possible to replace all users in a Custom Audience using a new list? What would be the best way to do this?
This one worked for me:
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.customaudience import CustomAudience
from random import randint
email_sha265 = '<sha265>'
list_id = '<list_id>'
client = FacebookAdsApi.init(
_app_id,
_app_secret,
_access_token
)
audience = CustomAudience(list_id)
session_id = randint(1000000, 9999999)
params = {
"session": {
"session_id": session_id,
"batch_seq":1,
"last_batch_flag": "false"
},
"payload": {
"schema":"EMAIL_SHA256",
"data":
[
email_sha265
]
}
}
# make the call
audience.create_users_replace(params=params)
Response:
<CustomAudience> {
"audience_id": "<list_id>",
"invalid_entry_samples": {},
"num_invalid_entries": 0,
"num_received": 1,
"session_id": "4847542"
}
Check this source code for more information:
https://github.com/facebook/facebook-python-business-sdk/blob/main/facebook_business/adobjects/customaudience.py
And the FB Docs:
https://developers.facebook.com/docs/marketing-api/audiences/guides/custom-audiences/#replace-api

Zoom api problem - invalid acces token - JWT

import requests
import json
import jwt
import datetime
APİ_KEY = "100 percent correct api key"
APİ_SECRET = "100 percent correct api secret"
payload = {
'iss':APİ_KEY,
'exp':datetime.datetime.now() + datetime.timedelta(hours=2)
}
token = jwt.encode(payload, APİ_SECRET)
print(token)
endpoint = "https://api.zoom.us/v2/users/my_e-mail_is_written_here/meetings"
myData = {
"headers": {
"authorization":"Bearer "+token,
"content-type":"application/json"
},
"body": {
"topic":"denemex",
"type":2,
"start_time":"2021-05-05T13:20",
"duration":"40",
"password":"1234"
}
}
zoom_r = requests.post(endpoint, data=json.dumps(myData))
print(zoom_r.status_code)
print(zoom_r.text)
I wanted to do a simple experiment with python like this, but I get an "invalid acces token" error, what could be the reason?
I thought a little more about my problem and solved the problem by changing the code as follows:
import requests
import json
import jwt
import datetime
APİ_KEY = "my api key"
APİ_SECRET = "my api secret"
payload = {
'iss':APİ_KEY,
'exp':datetime.datetime.now() + datetime.timedelta(hours=2)
}
token = jwt.encode(payload, APİ_SECRET)
endpoint = "https://api.zoom.us/v2/users/my_e-mail_is_written_here/meetings"
myData = {
"topic":"denemex",
"type":2,
"start_time":"2021-05-05T13:20",
"duration":"40",
"password":"1234"
}
headers = {"Content-Type":"application/json", "Authorization":"Bearer "+ token}
zoom_r = requests.post(endpoint, headers=headers, data=json.dumps(myData))
print(zoom_r.status_code)
print(zoom_r.text)

How we can create dataproc cluster using http request, getting error Expected OAuth 2 access token,

I am new in Python and airflow. I want to create a dataproc cluster using an http request inside a pythonoperator task. See the below code:
def create_cluster():
API_ENDPOINT = "https://dataproc.googleapis.com/v1beta2/projects/trim
-**********/regions/us-central1-b/clusters"
data = {
"projectId": "trim-**********",
"clusterName": "cluster-1",
"config": {
"configBucket": "",
"gceClusterConfig": {
"subnetworkUri": "default",
"zoneUri": "us-central1-b"
},
"masterConfig": {
"numInstances": 1,
"machineTypeUri": "n1-standard-1",
"diskConfig": {
"bootDiskSizeGb": 500,
"numLocalSsds": 0
}
},
"workerConfig": {
"numInstances": 2,
"machineTypeUri": "n1-standard-1",
"diskConfig": {
"bootDiskSizeGb": 100,
"numLocalSsds": 0
}
}
}
}
r = requests.post(url=API_ENDPOINT, data=data)
pastebin_url = r.text
print("The pastebin URL is:%s" % pastebin_url)
But I am getting an error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
What would be the solution for this error? Thanks in advance.

Why can I only make GET requests and not POST requests with this python code?

I'm trying to get this Etrade stuff up an running.... so far i have:
from rauth import OAuth1Service
import webbrowser
def getSession():
# Create a session
# Use actual consumer secret and key in place of 'foo' and 'bar'
service = OAuth1Service(
name = 'etrade',
consumer_key = 'cabf024eaXXXXXXXXX7a0243d8d',
consumer_secret = '3d05c41XXXXXXXXX1949d07c',
request_token_url =
'https://etws.etrade.com/oauth/request_token',
access_token_url =
'https://etws.etrade.com/oauth/access_token',
authorize_url = 'https://us.etrade.com/e/t/etws/authorize?
key={}&token={}',
base_url = 'https://etws.etrade.com')
# Get request token and secret
oauth_token, oauth_token_secret = service.get_request_token(params =
{'oauth_callback': 'oob',
'format': 'json'})
auth_url = service.authorize_url.format('cabf0XXXXXXXXXa0243d8d',
oauth_token)
webbrowser.open(auth_url)
verifier = raw_input('Please input the verifier: ')
return service.get_auth_session(oauth_token, oauth_token_secret,
params = {'oauth_verifier': verifier})
session = getSession()
This authentication process works perfectly fine and allows me to do get/delete requests but when I attempt to make post requests:
url =
'https://etwssandbox.etrade.com/order/sandbox/rest/previewoptionorder'
para = {
"PreviewOptionOrder": {
"-xmlns": "http://order.etws.etrade.com",
"OptionOrderRequest": {
"accountId": "83550325",
"quantity": "4",
"symbolInfo": {
"symbol": "AAPL",
"callOrPut": "CALL",
"strikePrice": "585",
"expirationYear": "2012",
"expirationMonth": "07",
"expirationDay": "21"
},
"orderAction": "BUY_OPEN",
"priceType": "MARKET",
"orderTerm": "GOOD_FOR_DAY"
}
}
}
resp = session.post(url,data=para)
resp.text
I get an error:
Unauthorized request: consumer key is missing.
I've tried numerous things (granted I am new to this stuff). I tried authenticating using just requests to no avail and I tried passing the oauth1 object to the posts function as a kw argument. Any ideas?

Facebook Ad Management Python SDK returns "GraphMethodException"

I am trying to do a simple get of stats of ad campaigns. I thre this together from the documentation:
from facebookads.objects import AdUser
from facebookads.api import FacebookAdsApi
from facebookads.objects import AdAccount
my_app_id = 'xxx'
my_app_secret = 'xxx'
my_access_token = 'xxx'
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
me = AdUser(fbid='xxx')
account = AdAccount('xxx')
params = {
'start_date': '2014-09-01',
}
fields = {
'impressions',
'clicks',
'spent',
}
stats = account.get_ad_campaign_stats(fields=fields, params=params)
for stat in stats:
print stat
I am getting back a code:1 type: GraphMethodException back from the API.
The response loos like this:
Message: Call was not successful
Method: GET
Path: https://graph.facebook.com/v2.3/xxx/adcampaignstats
Params: {'fields': 'impressions,spent,clicks', 'start_date': '2014-09-01', 'summary': 'true'}
Status: 400
Response:
{
"error": {
"message": "Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
"code": 100,
"type": "GraphMethodException"
}
}
What am I doing wrong? Any help would be great. Thanks!

Categories

Resources