Search API Connector Documentation

Print

Import Facebook Page Data to Google Sheets

In this guide, we’ll walk through how to pull Facebook fan page data from the Facebook API directly into Google Sheets, using the API Connector add-on for Google Sheets. Facebook Pages serve as a business presence for many companies, so we want a way to grab some stats about what people are clicking and reading on these pages.

There are 2 ways to connect to the Facebook Pages API:

  • Preset “Connect” button (OAuth) premium
  • Personal access token. Please check the appendix for detailed instructions to retrieve your token.

Contents

Before You Begin

Click here to install the API Connector add-on from the Google Marketplace.

Part 1: Connect to the Facebook Pages API

If you haven’t connected API Connector to Facebook Pages before, you’ll first need to initiate the connection as follows:

  1. Open up Google Sheets and click Add-ons > API Connector > Manage Connections.
  2. In the list of available connections, find Facebook Pages and click Connect.
    fb-page-connect-img1
  3. You’ll be asked which Pages to connect. Click through to connect your account.
    fb-page-connect-img2
  4. You’ll then be returned to your Google Sheet, and can verify that your Facebook Pages connection is active in the Connections screen.

Part 2: Get your Facebook Page ID

We’ll need your Facebook Page ID for subsequent requests, so let’s get it now.

  1. In API Connector, click Add New or Create to access the Create screen, and enter the following URL into the API URL path field:
    https://graph.facebook.com/v12.0/mixedanalytics
    Where it says mixedanalytics, enter in your own page name instead. You should see your page name in the URL bar when you open up your Facebook page.
  2. From the OAuth dropdown, choose Facebook Pages.
  3. Choose a destination sheet and request name
  4. Click Run to see your Facebook page ID
    fb-page-connect-img4

Alternatively, get your Facebook Page ID from your Facebook Business Manager account.
fb-page-connect-img5

Part 3: Create Your API Request URL

Now that we have a Facebook Page ID, let’s access the latest posts and metrics from your Page.

  • API Root: https://graph.facebook.com/v12.0
  • Endpoint: /{page_id}/posts
  • Query Strings: ?fields=id,message,created_time,insights.metric(post_impressions,post_reactions_like_total,post_clicks)&limit=100

The “limit” parameter is optional but can be used to return more records (otherwise the default is 25). Putting it together, we get the full API Request URL:

https://graph.facebook.com/v12.0/507738226062106/posts?fields=id,message,created_time,insights.metric(post_impressions,post_reactions_like_total,post_clicks)&limit=100

Just substitute in your own Page ID.

Part 4: Pull Facebook Page Data into Google Sheets

Now let’s get that data into Sheets.

  1. Back in the Create tab, enter the Request URL we just created.
    fb-page-data-img1
  2. Choose Facebook Pages from the OAuth dropdown menu. If you have access to multiple pages, make sure you’ve selected the page matching the page ID in your URL.
    fb-page-data-img2
  3. We don’t need any extra headers so just leave that section blank.
  4. Create a new tab and click Set current to choose that tab as your data destination.
  5. (Optional) Facebook sends a ton of data back in the response. To clean it up we can use a JMESPath filter to reduce the number of fields. Just copy/paste this expression into the JMESPath field:
    data[].{id:id,message:message,created_time:created_time,insights:insights.data[].{name:name,values:values}}
    fb-page-data-img3
  6. Click Run. A moment later you should see your most recent posts and post stats populate your Google Sheet.
    fb-page-data-img4

For an even more condensed report, you could use this JMESPath which puts the field name into the header: data[].{id:id,message:message,created_time:created_time,
post_impressions:insights.data[?name=='post_impressions'].values,
post_reactions_like_total:insights.data[?name=='post_reactions_like_total'].values,
post_clicks:insights.data[?name=='post_clicks'].values}

Part 5: More Example API URLs

Facebook’s API provides a lot of different endpoints and metrics. I’ve summarized some useful endpoints below, but for full information on setting up your queries, you can check Facebook’s official page insights documentation.

In addition, you can use API Connector’s API Library while in the add-on to easily pull up most of these sample URLs (and many others).

Examples:

Retrieve most of the default metrics from your FB page’s Insights Overview summary tab

When you navigate to www.facebook.com/YOUR_PAGE/insights/, you should see an insights summary page like this

fb-page-img20

You can use the following API request URL to pull in most of these metrics to your sheet:

https://graph.facebook.com/v12.0/{page_id}/insights?metric=page_total_actions,page_views_total,page_preview_total,page_fan_adds_unique,page_impressions_unique,page_post_engagements,page_video_views,page_daily_follows_unique&date_preset=yesterday&period=week
fb-page-img21

Get the current count of total FB page likes from the API

https://graph.facebook.com/v12.0/{page_id}/insights?metric=page_fans

Get count of total FB page likes by day for a time range (the “since” and “until” parameters contain the start and end dates). You can only query 90 days at once when using the since/until parameters.

Note: this request was run in “compact” mode. The default “single row” report style would display each day’s data in its own column.

fb-page-img22

https://graph.facebook.com/v12.0/{page_id}/insights?metric=page_fans&period=day&since=1577836800&until=1580428800
The Facebook Insights API requires dates to be entered as UNIX timestamps. In Sheets, you can convert a regular date in cell A1 to a UNIX timestamp with the formula =(A1-DATE(1970,1,1))*86400.

If you want to make a dynamically updating date range, add a dynamic date formula like =today()-1 to one cell, add a second cell that converts it to UNIX with the =(A1-DATE(1970,1,1))*86400 formula, and then reference that UNIX timestamp in your API request URL. Every time the date changes, your URL will update automatically.

In some of the examples above, you can see parameters for ‘date_preset’ and ‘period’. ‘Date_preset’ lets you select a date range for reporting, such as today, yesterday, this_month, last_month, etc. ‘Period’ allows you to aggregate data over certain predefined periods (day, week, days_28, month, lifetime).

Part 6: Handle Pagination

  1. By default Facebook limits the number of results in a single response (usually to 25 records) as described here: https://developers.facebook.com/docs/graph-api/using-graph-api/#paging. To get more records, you can add &limit=100 to the end of your URL.
  2. If you have more than 100 records, then you’ll need to cycle through the results in batches of 100. With API Connector you can loop through automatically using pagination handling (paid feature).
    • API URL: enter your request URL, making sure to include limit=100
    • Pagination type: cursor
    • Next token parameter: after
    • Next token field: paging.cursors.after
    • Number of pages: enter the number of pages you’d like to fetch
      fb-ads-img21

Appendix: Connect with a Facebook Access Token

This is an alternative to the method described above. Instead of authenticating through API Connector’s OAuth connection manager, you will get your own token and connect with that instead.

Note that the process for getting Facebook access tokens isn’t difficult, but it is quite long and convoluted as there are several kinds of tokens: User Access Tokens, App Access Tokens, and Page Access Tokens. Further, tokens are valid for different lengths of time, and Page Access Tokens are dependent on User Access Tokens. There are many different approaches to retrieve these tokens, but the following method should be the most straightforward. The good part is, you only need to do this process ONCE, as the token you get will last forever!

Step 1: Get your Facebook API User Access Token

  1. Begin by navigating to https://developers.facebook.com/, and click My Apps.
    fb-page-img1
  2. Click + New App
    fb-page-img2
  3. Facebook will ask you who is using your app. Choose “Manage integrations for your business”. This tells Facebook it’s just for your own private use.
    fb-page-app-audience
  4. Next, they will ask you for your app type. Choose Business and click Next.fb-page-img3
  5. Finally, enter your app details. You can call your app anything, as long as it doesn’t include any terms related to Facebook’s trademarks. We’ll just call our app Pages for Sheets. Enter a contact email addres and click Create App.
    fb-page-img4
  6. You’ll be directed into your Developer dashboard. You don’t need to do anything in this dashboard. Instead, open up the Facebook Graph API Explorer
  7. Under ‘Facebook App’, select the app you just created. Click Get User Access Token from the drop-down menu.
    fb-page-img5
  8. A modal will appear, prompting you to login. Click Continue.
    fb-page-img6
  9. Under ‘permissions’, you should now see ‘public_profile‘, meaning your token provides access to public information about yourself. Click the dropdown menu and add the permissions ‘pages_read_engagement‘ (located under Events Groups Pages) and ‘read_insights‘ (located under ‘Other’).
    fb-page-img7
  10. Now click Generate Access token.
    fb-page-img8
  11. You’ll see a couple modals prompting you to continue and to allow your app to access your Facebook Page and App insights, just click through these until you see a notification that the linking is complete.
    fb-page-img9
  12. You should now see your new access token in the Graph API Explorer. However it’s a short-lived access token and only lasts for 1 hour. We can extend it by clicking the small blue icon next to it, and then clicking Open in Access Token Tool:
    fb-page-img10
  13. At the bottom of this page, click Extend Access Token.
    fb-page-img11
  14. This will produce a long-lived User token. Copy it to your clipboard. You can also take note of your page ID here.
    fb-page-img12

Step 2: Get your Permanent Page Token

  1. Return to the Facebook Graph API Explorer. Paste the long-lived User token you just got into into the “Access Token” field.
    fb-page-img13
  2. Now in the URL field, erase what’s already there and type in YOUR_PAGE_ID?fields=access_token. You can get your Page ID as shown above, or get it by navigating to your Facebook page, clicking About, and scrolling down until you see ‘Page ID’. Click Submit.
    fb-page-img14
  3. You’ll now see a new token returned. This is your permanent Page token! Finally!! That means you’ll never have to go through the above steps again, so copy it down and keep it safe.
    fb-page-img15
  4. You can verify that this token is permanent by copying and pasting it into the Access Token Debugger. Click Debug, and make sure you see the following:
    • an App ID. You should your app listed at the top. If this is missing, you missed clicking through some of the required modals earlier on and need to go through these steps again 🙁
    • Type = Page (not User). You’ll need a page token to get access to all the page data.
    • Expires = Never. Even though it says Data Access Expires in 3 months, the permissions we’ve requested are explicitly exempted from this (documented here).
      fb-page-img16

Step 3: Use the Access Token

To use your Facebook token, append it to the end of your requests, like this:

https://graph.facebook.com/v12.0/{page_id}/posts?fields=insights.metric(post_impressions,post_reactions_like_total,post_clicks)&access_token=YOUR_TOKEN

Since you’re connecting with a token, leave OAuth set to None.

Previous Import Facebook Leads to Google Sheets
Next Import Financial Modeling Prep Data to Google Sheets

79 thoughts on “Import Facebook Page Data to Google Sheets”

  1. Is there a way to bring in insight information alongside the individual posts? So, after section 4 when you bring in all of the latest Facebook posts, is it possible to have additional columns with impressions, post likes etc?

    Reply
    • Hi Michael, you can do that by creating an API URL like this:
      https://graph.facebook.com/YOUR_PAGE_ID/posts?fields=id,message,insights.metric(post_impressions,post_reactions_like_total)&access_token=YOUR_PAGE_TOKEN

      Substitute in your own page ID and access token, and you’ll see a list of all your page posts alongside impressions and likes.

      Reply
    • The regular /feed endpoint will include data for any videos you’ve posted, but if you want videos only, you can make a request to the /videos endpoint. You can add in the fields you want as described in the video endpoint documentation at https://developers.facebook.com/docs/graph-api/reference/video/.
      For example, a request to
      https://graph.facebook.com/v5.0/{account}/videos?fields=title,description,embed_html,length,picture&access_token={token} would return the titles, descriptions, HTML, video length, and thumbnail for all your videos. There’s also a ‘content_tags’ parameter listed in the documentation, but it only returns a numeric value so I’m not sure how useful it is.

      Reply
      • So I believe it’s custom_labels but for some reason this isn’t working?

        https://graph.facebook.com/v5.0/{pageid}/videos?fields=id,title,description,custom_labels,length,is_crosspost_video,permalink_url,picture,&access_token={access token}

  2. Amazing, thank you, I’ll give it a try! I’ve scheduled the data to run every hour but it’s giving me the whole output again, instead of just anything new – is it possible to change this?

    Reply
    • API Connector doesn’t check the data before printing it into the sheet, so you can either use append mode and construct your URLs so that they only pull in new data (most APIs provide some mechanism of paging where you limit data pulls by date or ID), and/or you can use Google Sheet functions like UNIQUE() to dedupe on the front end.

      Reply
  3. First off just want to say this is a brilliant add-on!

    I’m having a go at bringing in Facebook video insights, but it’s displaying in a weird way:

    Using the exmapl;e posted above bringing in video insights, it’s displaying them very strangely, almost in multiple rows rather than columns folr each video, so it’;s mixing up the data?

    Reply
    • Thanks a lot, I appreciate that : ) As for mixing up the data, I’m not exactly sure what you’re seeing. To me it looks all right (if complicated), with each metric name followed by its count in the subsequent column. You can try changing the Report Style for a different JSON-to-Sheets algorithm, or limit the number of metrics you pull in at once so that the output doesn’t get so complex. This API wasn’t designed to be consumed in Sheets, so Facebook didn’t put much thought into producing JSON that looks clean when it’s flattened out.

      Reply
  4. Hi Ana,

    Great article, thanks. Just one question. I’ve seen that Facebook requested you for some permissions that you didn’t have (manage_pages and read_insights). How it was possible to move on without this permissions?

    Thank you!

    Reply
    • Hey John, those permissions are only required if you’re developing and publishing an app for other people to use (documentation). So basically we don’t need to worry about it because we’re the only ones using our apps.

      Reply
  5. Any ideas how to convert the datetime from the first column to normal date and time columns in sheets? Facebook API spits out YYY-MM-DDTHH:MM:SS+0000 (HHs in UCT). I would love to convert to local date and time, but the only hypothetical solution I’ve come up with is pretty complicated.

    Reply
  6. The column “comments » data » from » name” is blank for me. Is there a way to get the name of the Facebook user that left the comment?

    Reply
    • I checked the documentation and it seems that the name field should contain the name of the user who left the comment. If it’s blank, that means it’s not available for some reason, I suspect it’s related to some privacy-related changes.

      Reply
    • Not all metrics can be viewed weekly, you can see allowable periods by checking the “values for ‘period'” column in the FB documentation. So in those cases, just run a query like this that returns data by day, and then you can sum it on your end to get a weekly value.
      https://graph.facebook.com/PAGE_ID/insights/?metric=page_fan_adds_unique&date_preset=this_year&period=day&access_token=TOKEN
      Btw, I suggest switching to compact mode to make the response output easier to read.

      Reply
  7. Hi thanks for do this content im very apreciate and i have a feedback for you in the step 1 part 6
    Old Permission =manage_pages now is

    pages_manage_ads

    pages_manage_metadata

    pages_read_engagement

    pages_read_user_content

    Reply
  8. Hi,

    I like the simplicity of the tool for setting it up to get the Facebook Data, I am running into a problem, and I tried a few times today.

    Request failed: DNS error:

    Thanks,
    Neil

    Reply
    • A DNS error means the server isn’t responding, but I think it’s very unlikely that Facebook’s server has a problem. Therefore, I’d double-check that you’ve entered the correct hostname. Please feel free to share your sheet or send me a screenshot of your setup if you’d like me to take a look.

      Reply
  9. Hi Ana, I need a paid service from you which is: a simple app that exports all my Facebook page likers to Google spreadsheet. Can you do that to me ? thanks

    Reply
    • Hi there, I don’t believe the Facebook API provides this data. If you check https://developers.facebook.com/docs/graph-api/reference/object/likes, it says “Due to privacy concerns, a User or Page can only query their own likes.”
      You can still get this data from the interface by opening Facebook, navigating to your Page, clicking Settings, and then clicking the People and Other Pages tab in the left column. You may be able to find some apps that automate this process through web scraping.

      Reply
  10. Hi Ana, thank you very much for this article. It s so cool your step by step.

    I was just wondering… is the free API able to pull public information from other profiles than mine? I mean number of posts and number of fans…

    Thanks for sharing! 🙂

    Reply
    • Thank you for the comment, I’m glad you like the article! That’s a good question. The method above does NOT let you get data from other profiles, it’s only for pages of which you’re an admin. Public data is only available if you create an app that a) requests Page Public Content Access permission and b) successfully passes Facebook’s app review process (info).

      Reply
    • Glad you liked it! The first example in the article (https://graph.facebook.com/v7.0/507738226062106/feed?access_token=EAA...) returns post ID, title, and date, are you looking for something else?

      Reply
  11. Hello, Anna.

    First of all, thank you for the wonderful tutorials. I tried to do it exactly as you said on the blog. However, I got this error message and there isn’t data imported to the Google Sheet. I was stuck in the Part 4. It said:

    Status
    Request failed: Server responded with an error (400) show response
    {“error”:{“message”:”(#100) Pages Public Content Access requires either app secret proof or an app token”,”type”:”OAuthException”,”code”:100,”fbtrace_id”:”ANWpWogFTk6IERheBeZ4945″}}

    Could you please help me?

    Reply
    • Hi Ifa, you’re welcome 🙂 Sorry it didn’t work for you. I just started from scratch and went through the steps in the article all the way from the top to test if anything had changed. Everything still worked for me as written, so I’m not sure what the issue is exactly. But based on the error message, I think you may have entered in the Facebook Page ID of a page you don’t have access to. By Facebook Page ID, I mean the value that goes here:
      https://graph.facebook.com/v8.0/FB_PAGE_ID/feed?access_token=EAA...

      Can you please go through the process again, making sure you’ve selected that Facebook page during the linking process, and have entered the correct ID for that page? (you can see your page ID when logged in as admin on the About section of your FB page).

      Reply
    • Facebook doesn’t provide this information via the API due to privacy concerns (documented here). However, you can get this data by navigating to your Facebook Page, clicking “Settings”, and then clicking the “People and Other Pages” tab in the left column. That will show you a list of people who have liked your page.

      Reply
  12. Dear Ana, thank you for a great tutorial!
    Is it possible to obtain information from other users’ profiles in this way?
    I do research on banking activity in social media, so I need data on the number of posts and likes on bank profiles.

    Reply
    • Hi Ilona, sorry, the official API only allows you to get data for pages of which you are an Admin. If you need data on posts and likes from other profiles, you would need to look into a web scraping tool instead. Hope that helps!

      Reply
    • Hey Rhys, sorry, I’m not really sure if this is possible. I haven’t done it before myself and this page says you can only query your own comments. It may be possible if you get approval for “Page Public Content Access”.

      Reply
  13. Hi Ana,

    Thanks for this! Very Useful.

    I am trying to use the following path to extract daily data for specific metrics from my Facebook business page, starting from Jan 1 2021. Essentially, I want a new row added for each day’s metrics and want this to run daily automatically. Could you please let me know what needs to be added to make this possible?

    https://graph.facebook.com/v10.0/PAGE_ID/insights?metric=page_impressions_organic,page_impressions_paid,page_impressions_organic_unique,page_impressions_paid_unique,page_post_engagements,page_daily_follows_unique&date_preset=last_year&period=day&access_token=TOKEN_NAME

    Also, is there any way to add a column for the date that the data was pulled?

    Thank you in advance!

    Reply
    • Hi Amy, you can get daily metrics by changing your date preset to yesterday, like this:
      https://graph.facebook.com/v10.0/PAGE_ID/insights?metric=page_impressions_organic,page_impressions_paid,page_impressions_organic_unique,page_impressions_paid_unique,page_post_engagements,page_daily_follows_unique&date_preset=yesterday&period=day&access_token=TOKEN_NAME

      To add a column for the date the data was pulled, you can turn on the “Add timestamp” option (located under the Output options button). You can also switch to append mode there so new data gets appended to the end of your report.

      To run it automatically you can check out our (paid) scheduling feature.

      The remaining challenge is that Facebook returns the data as a block rather than in a single row. To address that, I suggest making a second summary sheet. The summary sheet can then use formulas like VLOOKUP to pull data from your data source sheet and structure it the way you want. Another option is to use a JMESPath expression to restructure the data directly, for example this JMESPath expression would print metrics side by side into a single row:
      {page_total_actions: data[?name==`page_total_actions`].values[].value,
      page_views_total: data[?name==`page_views_total`].values[].value,
      page_fan_adds_unique: data[?name==`page_fan_adds_unique`].values[].value,
      page_post_engagements: data[?name==`page_post_engagements`].values[].value}

      Reply
  14. Hi Ana,

    I created a Facebook/Instagram token but now I want to delete it and change it completely. Could you please tell me how I can rewrite the token?

    Thank you,
    Liz

    Reply
    • So essentially what I want to do is to actually keep all the settings as they are for the App that I created but to just generate a new token, replacing the old one.

      Thanks again,
      Liz

      Reply
      • If you’re creating a new token, I would just delete your old app and go through the process again. You could try jumping into the process part way through (like after the user token) but I haven’t tested that myself.

  15. I would like to extract the leads from the FB business account. I have tried using the form ID to get data. it return no records. but it has lead data exist.
    The other way using Adgroup id which I couldn’t get from which section of FB console.

    FB API doc has api url to retrieve lead but does not have much route to explanation.

    Do you have any idea how to download lead using API? It is mostly connected to the Ad. but no way to get form id or possible route key for leads.

    Reply
  16. Hi Ana,

    I’ve followed the step-by-step directions and tried using the template, but none of the page insights are populating in Sheets. The data for PAST WEEK PAGE PERFORMANCE all shows as #N/A. The date and post text populate for FACEBOOK POST INSIGHTS (ALL TIME) but impressions, likes, and clicks all appear as #N/A. What could be my issue?

    Thanks,
    Tyler

    Reply
    • Hey Tyler, I’m not sure but I suspect it’s because your fields are coming through a bit differently and breaking the VLOOKUP formulas in row 20.
      If you like, feel free to share your sheet with me. I’ll be happy to take a look and fix it for you

      Reply
  17. Hi! Ana

    What might I doing wrong? I got this error message:

    1) PageInsights: Completed with errors
    – We received an error from the API server (400) – Page authentication may not match, please verify the Page selection show response
    {“error”:{“message”:”(#190) This method must be called with a Page Access Token”,”type”:”OAuthException”,”code”:190,”fbtrace_id”:”AwHtUsI-QyjU4W5fM8h4vG2″}}

    I’m trying to pull my page fans, with this URL:
    https://graph.facebook.com/{Page ID}/insights?metric=page_fans&period=day&since=1625097600&until=1630627200

    Reply
    • Sounds like the page ID you entered in the URL is a different from the page shown underneath the OAuth dropdown. If you have access to multiple Facebook pages, please make sure you select the correct one from the dropdown menu when making your calls, since each page is only authorized to see its own data.

      Reply
    • Hi David, sorry, I don’t know how to get Facebook page comments from the API. It might be possible but I keep getting a permissions error when I try. So, for now I have to say you can’t do it with this tool, sorry about that.

      Reply
    • I just tested and everything still worked for me as written. We automatically update the version number for OAuth connections, but if you’re using an API key you would need to update the version number in your request URL yourself. Can you please clarify what kind of error or issue you’re seeing?

      Reply
  18. How do I pull Facebook page insights for the previous month to only output totals for each metric? I used the formula below but it’s outputting each day as separate columns instead of a total for the month. Should I use something different than “date_preset=last_month”? I’m trying to set it up so I can schedule it to run every month, but it will make it difficult to add up columns when months have different days.

    https://graph.facebook.com/v12.0/{page-id}/insights?metric=page_total_actions,page_views_total,page_preview_total,page_fan_adds_unique,page_impressions_unique,page_post_engagements,page_video_views,page_daily_follows_unique&date_preset=last_month&period=month

    Reply
    • Yup, exactly, can you please change date_preset=last_month to date_preset=yesterday? Then it will just show you a single day’s data rather than each day within the preset period.

      Another option would be to use “since” and “until” with a range of a single day. It’s an extra step to set up but will let you be really precise about which day you want to pull data for. You can reference cells to pass the since/until values in dynamically so they always represent, say, the last day of the month.

      Reply

Leave a Comment

Table of Contents