Skip to content

Instantly share code, notes, and snippets.

@unrelentingfox
Created June 23, 2021 06:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unrelentingfox/ac2e5742d981a189f3138978f1a2a5af to your computer and use it in GitHub Desktop.
Save unrelentingfox/ac2e5742d981a189f3138978f1a2a5af to your computer and use it in GitHub Desktop.
An example of how you can use the facebook api to populate a google sheet.
// https://www.benlcollins.com/apps-script/api-tutorial-for-beginners/
function main() {
let accessToken = "YOUR_ACCESS_TOKEN"
let fields = "account_id,account_name,date_start,date_stop,impressions,spend"
let accountIds = getAccountIds(accessToken)
let jsonData = getAdInsights(accountIds, fields, accessToken)
let sheet = SpreadsheetApp.getActiveSheet()
let dataKeys = Object.keys(jsonData[0])
let dataArray = convertToArray(dataKeys, jsonData)
dataArray.unshift(dataKeys)
let range = sheet.getRange(1,1, dataArray.length, dataKeys.length)
range.setValues(dataArray)
}
function convertToArray(dataKeys, jsonData) {
Logger.log(dataKeys)
return jsonData.map(entry => {
Logger.log(entry)
return dataKeys.map(key => entry[key])
})
}
function fbRequestJsonData(url) {
var response = UrlFetchApp.fetch(url)
if (response.getResponseCode() != 200) {
throw `ERROR: Failed to make request ${url}, response code:` + response.getResponseCode()
}
return JSON.parse(response.getContentText()).data
}
// https://developers.facebook.com/docs/marketing-api/connectionobjects/v11.0
function getAccountIds(accessToken) {
return fbRequestJsonData(`https://graph.facebook.com/v11.0/me/adaccounts?access_token=${accessToken}`).map(account =>{
return account.id
})
}
// https://developers.facebook.com/docs/marketing-api/insights/
function getAdInsights(accountIds, fields, accessToken) {
return accountIds.flatMap(id => {
return fbRequestJsonData(`https://graph.facebook.com/v11.0/${id}/insights?access_token=${accessToken}&fields=${fields}`)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment