Package: facebookinsights
``facebook-insights`` is a command-line utility that makes it easier tointeract with `Insights metrics in the Facebook GraphAPI <https://developers.facebook.com/docs/graph-api/reference/v2.2/insights>`__.Python users can also directly access the API wrapper that the CLI isbuilt on.-  **Authentication.** OAuth2 is a bit of a pain and we've made iteasier.-  **Querying.** Query page and post insights with simple command-lineparameters or through a pythonic interface.-  **Reporting.** Outputs simple timeseries of the data rather thanverbose API responses.-  **Portability.** JSON output means you can analyze the data in anylanguage from R to Julia to Ruby to Java.**Development status:** the Python interface to ``facebook-insights`` isclose to stable, but some things might change and others still needpolish. The command-line interface is still very much a work in progressand you probably shouldn't try to use it yet.Usage-----Authentication^^^^^^^^^^^^^^.. code:: pythonimport osimport facebookinsights as fi# prompt for credentials on the command-line,# get access to one or more pagespages = fi.authenticate()# alternatively, pass an existing page tokenpage = fi.authenticate(token=os.environ['FACEBOOK_PAGE_TOKEN'])Scroll down to find out more about authentication.Page Posts^^^^^^^^^^Facebook provides Insights data for the page as a whole (followercounts, impressions across all stories etc.), for all page posts takentogether (likes for all page posts published last week etc.) and forindividual posts (video plays for one particular post etc.).. code:: python# return a range of page postslatest = page.posts.latest(10).get()today = page.posts.range(days=1).get()quarter = page.posts.range(months=3).get()# look for a particular post insteadpage.posts.find(url='http://fusion.net/story/37894/narcotrafficking-for-dummies-check-out-these-pics-of-bizarre-drug-smuggling-fails/')Reporting Periods^^^^^^^^^^^^^^^^^For many metrics, Facebook Insights includes historical data, so you cansee e.g. how your page's fans have increased or decreased over time.However, for some page metrics and most post metrics, only lifetimemetrics are available, which represent the current state of things... code:: python# for many metrics, historical data is available, with daily, weekly# and 4-weekly rollups, accessible through `daily`, `weekly` and# `monthly` methodspage.insights.daily(['page_impressions', 'page_fan_adds']).range(months=1).get()# for other metrics, there's only a lifetime totalpost.insights.lifetime('post_stories').get()# for some, it's the other way around: no total, only the daily numbersfor country_data in page.insights.daily('page_places_checkins_by_country'):print country_dataAlso note that some metrics are updated roughly every 15 minutes whereasothers can lag behind up to a day. Metrics postfixed with an asterisk inthe `Facebook Graph APIdocumentation <https://developers.facebook.com/docs/graph-api/reference/v2.2/insights>`__indicate frequently updated metrics.**Note:** currently, ``facebook-insights`` will not throw an error ifyou ask for a metric at an impossible granularity. Instead, Facebookwill return data at the granularity (often lifetime) that it canprovide.Metrics^^^^^^^It is possible to ask for one or more metrics in particular... code:: python# results will be returned as a single scalar valuepage.insights.lifetime('page_impressions').get()# results will be returned as an arraypage.insights.lifetime(['page_impressions', 'page_fan_adds']).get()# default metrics subsetpage.insights.lifetime().get()If no metrics are specified, the Facebook Graph API will return a usefulsubset by default.Query Results^^^^^^^^^^^^^.. code:: python# metrics are classless, rows are named tuples# column plucking is possiblepost.lifetime()[0].page_fanspost.daily()['page_fans'][0]post.daily('page_fans')[0]Lower-level^^^^^^^^^^^``facebook-insights`` is built on the`FacePy <https://github.com/jgorset/facepy>`__ library, and you may passcertain low-level options to FacePy when executing queries:.. code:: pythonpost.daily('page_fans_online_per_day', retry=3)Terminology------------  **page**: a Facebook (fan) page-  **page post**: a post to a Facebook page-  **story**: a user interaction with a page, e.g. "Mike liked thispage." or "Jeb shared this post with his friends."-  **story type**: the type of interaction a user has with a page, e.g.a checkin, a mention or a like.-  **storyteller**: a user who interacts with a page (e.g. by liking apage post)-  **impression**: a view of either the page or a page post-  **engaged user**: a user who clicked anywhere on a page or a pagepost-  **consumption**: a click on a page or a page post; an engaged usercan show up as one or more consumptions-  **fan**: a user who has liked your page and will usually see it intheir feed. Similar to a Twitter follower.-  **unique**: count no more than once per user-  **organic**: impressions or interactions not the result of promotingyour post, as opposed to paid impressions and interactions-  **feedback**: positive feedback includes likes, shares and so on;negative feedback includes hiding, unliking and reporting spam.Most of this terminology applies both at the page level and at the pagepost level. For example:-  ``page_impressions_unique`` at the page level-  ``page_posts_impressions_unique`` for interactions with any page post-  ``post_impressions_unique`` about one particular postYou will find more detailed explanations of much of this terminology anda list of all story and feedback types in the `Facebook Graph APIInsightsdocumentation <https://developers.facebook.com/docs/graph-api/reference/v2.2/insights>`__,which is excellent.Page and Post objects---------------------Pending better documentation, to find out more about what properties andmethods are available on ``Page``, ``Post``, ``Picture`` objects, pleasetake a look at ``facebookinsights/graph.py``.To find out more detailed information about querying, look at``Selection``, ``PageSelection`` and ``InsightsSelection`` in``facebookinsights/graph.py``.Authentication in detail------------------------You cannot use the Facebook Graph API with your Facebook username andpassword. Instead, you must authenticate through oAuth, first getting auser access token and then using that token to find the access tokens tothe Facebook Pages for which you are an admin or for which you otherwisehave permission to view the insights data.Short-term~~~~~~~~~~Short term access (a couple of hours) is most easily gained through the`Graph API Explorer <https://developers.facebook.com/tools/explorer>`__.1. Go to the `Graph APIExplorer <https://developers.facebook.com/tools/explorer>`__2. Click on ``Get Access Token`` near the top of the page3. Navigate to the ``me/accounts`` endpoint by entering it and clickingsubmit4. Find and copy the page access token or tokens from the resulting JSONOn the command line:.. code:: sh# WARNING: suggested interface, not built yet# use a token on every requestinsights posts \--token <your token here> \--since 2014-08-01 \--until 2014-08-10 \--metrics post_impressions# use a saved token from a `~/.facebookinsights`# INI file insteadinsights posts \--profile <name>In Python:.. code:: pythonimport facebookinsights as fipage = fi.authenticate(token='your page token goes here')Long-term~~~~~~~~~It is also possible to ask Facebook for page tokens that remain validindefinitely unless revoked by the page owner.1. Go to the `Facebook Developers <https://developers.facebook.com/>`__portal, and click on ``Apps > Create a New App``2. Fill out the requisite information3. After being redirected to your app's settings page, grab the App IDand App Secret. Save them somewhere, e.g. as environment variables inyour ``~/.bashrc``4. Go to advanced settings and specify that your app is a``Native or desktop app``5. Lower down on the advanced settings page, add``http://localhost:5000/`` to the Valid OAuth redirect URIs.If you intend to make your app public at some point, there are variousother steps to go through: whitelisting callback URLs, going through theFacebook app approval process and so on.If on the other hand you just want to analyze your own Facebook Insightsdata, you'll probably never need to look at your app settings again.On your desktop^^^^^^^^^^^^^^^On the command-line, get authorization and save the resulting pagetokens:.. code:: sh# WARNING: suggested interface, not built yet# provide client_id and client_secretinsights auth <client_id> <client_secret># use a profile from a `~/.facebookinsights`# INI file insteadinsights auth --profile <name>In Python:.. code:: pythonimport facebookinsights as fi# this will launch a web browser to authenticatepages = fi.authenticate(client_id='your client id',client_secret='your client secret',)If no arguments to ``authenticate`` are specified, ``facebook-insights``will look for environment variables named``FACEBOOK_INSIGHTS_CLIENT_ID`` and ``FACEBOOK_INSIGHTS_CLIENT_SECRET``which correspond to the App ID and App Secret you got from your app'ssettings page earlier... code:: pythonimport facebookinsights as fi# this will launch a web browser to authenticatepages = fi.authenticate()``pages`` will be a list of ``Page`` objects. You can access a page'stoken with ``page.token``, which means you can make save those tokensfor later use. This is especially important for analyses and other codethat runs unattended, as getting new tokens through an oAuthauthorization process always requires user interaction.Here's an example that uses your system's keychain to store credentials:.. code:: pythonimport keyringimport jsonimport facebookinsights as fitoken = keyring.get_password('facebook-insights', 'test')if token:page = fi.authenticate(token=token)else:page = fi.authenticate()[0]keyring.set_password('facebook-insights', 'test', page.token)In a web app^^^^^^^^^^^^An example of how to integrate Facebook oAuth authorization in a Flaskweb app is provided in ``examples/server.py``. The process is verysimilar for Django and other Python web frameworks:-  One route that redirects to Facebook-  Another route that receives the authorization code from Facebook andexchanges it for a user token and subsequently for page tokens