Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Fetches and converts data between Facebook, Google+, Instagram, and Twitter native APIs, ActivityStreams, microformats2 HTML and JSON, Atom, and more.
Python HTML Other
Failed to load latest commit information.
granary facebook: handle wall posts inheriting privacy by setting AS 'to' fie…
old_apps redirect old *-activitystreams apps to
static Correct JS to populate URL for for microformats2 form
.gitignore ignore TAGS files from ctags/etags
.gitmodules switch from submodules to virtualenv, package w/setuptools for pypi fix atom module by correctly including templates/ subdir in … fix atom module by correctly including templates/ subdir in … set up CircleCI
README.rst update pypi version, and add Flickr to readmes add to make this a package fix search query param, take 2 search query bug fixes for silo demo handler
app.yaml ignore TAGS files from ctags/etags starting to redesign web app
circle.yml set up CircleCI
cron.yaml fix ereporter email addresses
googleplus_api_discovery.json use a canned G+ API discovery doc in tests instead of fetching over t…
requirements.txt add html2text to to match requirements.txt add html2text to to match requirements.txt factor out activitystreams.Handler.write_response() so it's reusable use mf2util's post type discovery implementation


granary Circle CI

Free yourself from silo API chaff and expose the sweet social data foodstuff inside in standard formats and protocols!


Granary is a library and REST API that converts between a wide variety of formats:

Try out the interactive demo:

License: This project is placed in the public domain.


All dependencies are handled by pip and enumerated in requirements.txt. We recommend that you install with pip in a virtualenv. (App Engine details.)

The library and REST API are both based on the OpenSocial Activity Streams service.

Let's start with an example. This code using the library:

from granary import twitter

is equivalent to this HTTP GET request:

They return the authenticated user's Twitter stream, ie tweets from the people they follow. Here's the JSON output:

  "itemsPerPage": 10,
  "startIndex": 0,
  "totalResults": 12
  "items": [{
      "verb": "post",
      "id": ",2013:374272979578150912"
      "url": "",
      "content": "Getting stuff for barbecue tomorrow. No ribs left! Got some nice tenderloin though. (@ Metro Plus Famille Lemay)",
      "actor": {
      "username": "evanpro",
        "displayName": "Evan Prodromou",
        "description": "Prospector.",
        "url": "",
      "object": {
        "tags": [{
            "url": "",
            "startIndex": 113,
            "length": 22,
            "objectType": "article"
          }, ...],
    }, ...]

The request parameters are the same for both, all optional: USER_ID is a source-specific id or @me for the authenticated user. GROUP_ID may be @all, @friends (currently identical to @all), @self, or @search; APP_ID is currently ignored; best practice is to use @app as a placeholder.

Paging is supported via the startIndex and count parameters. They're self explanatory, and described in detail in the OpenSearch spec and OpenSocial spec.

When using the GROUP_ID @search (for platforms that support it — currently Twitter and Instagram), provide a search string via the q parameter. The API is loosely based on the OpenSearch spec, the OpenSocial Core Container spec, and the OpenSocial Core Gadget spec.

Output data is JSON Activity Streams 1.0 objects wrapped in the OpenSocial envelope, which puts the activities in the top-level items field as a list and adds the itemsPerPage, totalCount, etc. fields.

Most Facebook requests and all Twitter, Google+, Instagram, and Flickr requests will need OAuth access tokens. If you're using Python on Google App Engine, oauth-dropins is an easy way to add OAuth client flows for these sites. Otherwise, here are the sites' authentication docs: Facebook, Flickr, Google+, Instagram, Twitter.

If you get an access token and pass it along, it will be used to sign and authorize the underlying requests to the sources providers. See the demos on the REST API endpoints above for examples.

Using the REST API

The endpoints above all serve the OpenSocial Activity Streams REST API. Request paths are of the form:


All query parameters are optional. FORMAT may be json (the default), xml, or atom, both of which return Atom. The rest of the path elements and query params are described above.

Errors are returned with the appropriate HTTP response code, e.g. 403 for Unauthorized, with details in the response body.

To use the REST API in an existing ActivityStreams client, you'll need to hard-code exceptions for the domains you want to use e.g., and redirect HTTP requests to the corresponding endpoint above.

Using the library

See the example above for a quick start guide.

Clone or download this repo into a directory named granary (note the underscore instead of dash). Each source works the same way. Import the module for the source you want to use, then instantiate its class by passing the HTTP handler object. The handler should have a request attribute for the current HTTP request.

The useful methods are get_activities() and get_actor(), which returns the current authenticated user (if any). See the individual method docstrings for details. All return values are Python dicts of decoded ActivityStreams JSON.

The microformats2.*_to_html() functions are also useful for rendering ActivityStreams objects as nicely formatted HTML.


Check out the oauth-dropins Troubleshooting/FAQ section. It's pretty comprehensive and applies to this project too. For searchability, here are a handful of error messages that have solutions there:

bash: ./bin/easy_install: ...bad interpreter: No such file or directory

ImportError: cannot import name certs

ImportError: cannot import name tweepy

File ".../site-packages/tweepy/", line 68, in _get_request_token
  raise TweepError(e)
TweepError: must be _socket.socket, not socket

Future work

We'd love to add more sites! Off the top of my head, YouTube, Tumblr,, Sina Weibo, Qzone, and RenRen would be good candidates. If you're looking to get started, implementing a new site is a good place to start. It's pretty self contained and the existing sites are good examples to follow, but it's a decent amount of work, so you'll be familiar with the whole project by the end.


Pull requests are welcome! Feel free to ping me with any questions.

You'll need the App Engine Python SDK version 1.9.15 or later (for vendor support). Add it to your $PYTHONPATH, e.g. export PYTHONPATH=$PYTHONPATH:/usr/local/google_appengine, and then run:

virtualenv local
source local/bin/activate
pip install -r requirements.txt
python test

If you send a pull request, please include (or update) a test for the new functionality if possible! The tests require the App Engine SDK.

If you want to work on oauth-dropins at the same time, install it in "source" mode with pip install -e <path to oauth-dropins repo>.

To deploy:

python -m unittest discover && ~/google_appengine/ update .

To deploy facebook-atom, twitter-atom, and instagram-atom after an granary change:

foreach s (facebook twitter instagram)
  cd ~/src/$s-atom/activitystreams && git pull && \
    cd .. && ~/google_appengine/ update .

To deploy the old * apps:

cd old_apps
rm -f app.yaml && ln -s app.twitter.yaml app.yaml && \
  ~/google_appengine/ update . && \
rm -f app.yaml && ln -s app.facebook.yaml app.yaml && \
  ~/google_appengine/ update . && \
rm -f app.yaml && ln -s app.instagram.yaml app.yaml && \
  ~/google_appengine/ update . && \
git co -- app.yaml

This ActivityStreams validator is useful for manual testing.

Related work

Gnip is by far the most complete project in this vein. It similarly converts social network data to ActivityStreams and supports many more source networks. Unfortunately, it's commercial, there's no free trial or self-serve signup, and plans start at $500.

DataSift looks like broadly the same thing, except they offer self-serve, pay as you go billing, and they use their own proprietary output format instead of ActivityStreams. They're also aimed more at data mining as opposed to individual user access.

Cliqset's FeedProxy used to do this kind of format translation, but unfortunately it and Cliqset died.

Facebook used to officially support ActivityStreams, but that's also dead.

There are a number of products that download your social network data, normalize it, and let you query and visualize it. SocialSafe and ThinkUp are two of the most mature. There's also the lifelogging/lifestream aggregator vein of projects that pull data from multiple source sites. Storytlr is a good example. It doesn't include Facebook, Google+, or Instagram, but does include a number of smaller source sites. There are lots of others, e.g. the Lifestream WordPress plugin. Unfortunately, these are generally aimed at end users, not developers, and don't usually expose libraries or REST APIs.

On the open source side, there are many related projects. php-mf2-shim adds microformats2 to Facebook and Twitter's raw HTML. sockethub is a similar "polyglot" approach, but more focused on writing than reading.


  • https kwarg to get_activities() etc that converts all http links to https
  • convert most of the per-site tests to testdata tests
Something went wrong with that request. Please try again.