Embedding API Sandboxes in Documentation

Last week I released a jQuery plugin called API Sandbox to help developers of web apps expose their API in a guided sandbox environment. The usage is simple. On a template, make sure there is a dedicated div element available to place a sandbox and then simply call the apiSandbox function on it.


This would create a nicely animated sandbox environment with proper fields for the parameters expressed in the path (in this case, one for user_id). API Sandbox supports generic URL parameters at the end of the API path, in addition to symbol wildcards anywhere in the path, preceded by a “:”.

There are a bunch of applications for this, and I’m still making improvements to the plugin, but I want to talk about one particularly cool application today. This plugin combined with the latest version of Redcarpet (2.0.0b), a Markdown parser, can allow you to easily embed sandboxes inline with your API documentation.

What’s so cool about the new version of Redcarpet is that instead of simply relying on the plugin author’s interpretation of how Markdown should be transformed into HTML, you can specify your own rendering rules and just let Redcarpet do all of the parsing. To easily embed sandboxes, I chose to override Redcarpet’s default rendering of links and change links to API paths into dynamic sandboxes. I created a subclass of Redcarpet::Render::HTML and created override methods for link and doc_header.

class DocsParser < Redcarpet::Render::HTML
  def link(link, title, content)
    if link.include? "SANDBOX: "
      path = link.gsub("SANDBOX: ","")
      id = path.gsub(/[\/?&=\[\]]/,"")
      rendered = "<div id='sandbox'>"
      rendered += content + "<div id='" + path + "' class='sandbox " + id + "'></div>"
      rendered += "</div>"
      link = link || ""
      title = title || ""
      content = content || ""
      rendered = "<a href='" +link + "'>" + content + "</a>"

  def doc_header
    "<script>new App.Views.Docs({ el: $('#main_content') });</script>"

All I did here was render a div element with the id of sandbox instead of a link when the path has a prefix of SANDBOX:, and then added in a script in the header of all generated documentation pages to load the script that changes the divs into sandboxes (the site I’m working on uses Backbone.js, hence the new App.Views.Docs).

Then you have to write an epic 2 lines of CoffeeScript code to turn all of the links into awesome API sandboxes.

$("div.sandbox").each ->
      $(this).apiSandbox "get", $(this).attr("id")

Not bad at all.

API Sandbox is just the first part of a CoffeeScript/SASS/Ruby API explorer I’ll be releasing over the next couple of weeks, so get excited.