February 13, 2012

How to embed Bitbucket source code on your Website

I recently had a conversation with Paul Knopf on Twitter regarding the best way to embed code on a web site.

Fabrik (what my blog runs on) uses Google Code Prettifier to format all code samples. This is made even easier by the fact that I use Markdown to write my posts.

One disadvantage to this approach is when referencing code that already exists in source control. If you’re a good blogger then every time you update the code in your repository, you’ll also need to update the blog posts that reference it.

Wouldn’t it be nice if you could just embed the code directly from your source control system?

Github Gists allow you to easily share/embed code snippets/pastes but there doesn’t seem to be straightforward way of sharing code directly from a github respository.

BitBucket do allow you to embed files in a repository but only for a specific changeset. Also the embed code is pretty awful.

Since Paul has already started working on a better way to embed code from github, I thought I would look at how we can make use of BitBucket’s REST API to embed the latest version (tip) of files in a repository.

The REST API includes a Source Resource for browsing directories in a repository and viewing files.

The URL format for viewing a file’s content is:

https://api.bitbucket.org/1.0/repositories/[username]/[repository-name]/src/tip/[path-to-file]

e.g:

https://api.bitbucket.org/1.0/repositories/jespern/django-piston/src/tip/piston/utils.py

By default this returns a JSON object like so:

{
    "data": "import time\nfrom django.http import HttpResponseNotAllowed, ...",
    "node": "7970b070f884", 
    "path": "piston/utils.py"
}

where “data” contains the contents of the file.

Using jQuery we can make a cross-domain AJAX request to the REST service and embed the code on our page.

The javascript code below converts all links with the class “embed” into embedded code:

© 2022 Ben Foster