Connecting to Facebook Ads api with python
Many have been asking how to connect facebook ads api with python. The need is usually to analyze the facebook ads data, visualize it or simply store it in a database for later use.
Here I will show a very quick way to pull facebook data with python.
You can connect directly to the api, here is the documentation: https://developers.facebook.com/docs/marketing-apis/ and use the python package. However a simpler way is to use windsor.ai connector service.
Then the steps are as follows.
- Grant access to Facebook ads in https://onboard.windsor.ai
- Select the fields and metrics you want to pull
- Use the built query in python to get your data
Step 1: Grant access to Facebook ads in https://onboard.windsor.ai
First you have to register, then you select Facebook ads and grant access.
2. Select the fields and build the query
3. Use the built query in python to get data
Here is a short python snippet that gets the data into a pandas dataframe and prints it:
import pandas as pd
api_key = 'APIKEY' # your api-key
# URL listing the fields you want to pull
api_url = 'https://connectors.windsor.ai/facebook?date_preset=last_7d&fields=date,campaign,clicks,spend&api_key=' + api_key
res = requests.get(api_url).json()
df = pd.DataFrame.from_dict(res['data'])
The output will then look like this:
date campaign clicks spend
0 2021-12-03 retageting APAC 1 2.87
1 2021-12-03 retargeting UK&CO 0 0.03
2 2021-12-04 retageting APAC 0 2.91
3 2021-12-04 retargeting UK&CO 0 0.04
And you can adjust the fields argument for any fields you would like to have. The full fields documentation is here: https://windsor.ai/connector/facebook-ads/