Z
Z
Zheka Dzecina2017-02-23 21:55:57
Python
Zheka Dzecina, 2017-02-23 21:55:57

How to generate batch request in facebook (marketing) api in python?

Hello!
I work with facebook (marketing) api and I need to generate a batch request using python-sdk. This is what the request looks like (in the documentation)
curl -F 'access_token=____'
-F 'batch=[
{
"method": "GET",
"relative_url": "/act_600335/reachestimate?currency=USD&targeting_spec={'countries': ['US']}"
},
{
"method": "GET",
"relative_url": "/act_600335/reachestimate?currency=USD&targeting_spec={'countries':['FR']}"
},
"relative_url": "/act_600335/reachestimate?currency=USD&targeting_spec={'countries':['US'],'zips':['94402']}"
}
]' https://graph.facebook.com
(taken from here https://developers.facebook.com/docs/marketing-api...
this is how it works but it's a curl variant how to do the same but in python this
is how it looks like with a normal request
params = {
'currency ': 'USD',
'optimize_for': AdSet.OptimizationGoal.offsite_conversions,
'targeting_spec': targeting_spec,
}
reach_estimate = account.get_reach_estimate(params=params)
facebook-python-sdk is poorly documented in using batch requests.
I've been trying to figure it out for a few days now, but nothing. Tell me, please, who knows.
Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Philipp, 2017-02-23
@zoonman

I am not very strong in Python, but you can look at the SDK sources.
https://github.com/facebook/facebook-python-ads-sd...

D
Dimonchik, 2017-02-23
@dimonchik2013

use PyCURL

Z
Zheka Dzecina, 2017-03-04
@Zhe1ka

as it turned out, the problem was very simple, but so non-obvious
working example of a batch request

batch_data = [
        {
            'method': "GET",
            'relative_url': "v2.8/act_668439229891890/reachestimate?currency=USD&optimize_for=OFFSITE_CONVERSIONS&targeting_spec={'geo_locations': {'location_types': ['recent', 'home'], 'countries': ['US']}}",
        }
    ]
    batch_result = []

    def callback(data):
        batch_result.append(data.json()['data']['users'])

    api_batch = api.new_batch()

    for item in batch_data:
        api_batch.add(
            method=item['method'],
            success=callback,
            relative_path=item['relative_url']
        )

    api_batch.execute()

I specified the api version without the letter "v"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question