Using Cloudant’s Heroku Add-on

Alan Hoffman

August 05, 2010

Heroku has recently jumped with both feet into the NoSQL world, providing add-ons for many different NoSQL data stores to complement it’s easy ruby platform. We’re very excited to be able to offer CouchDB 1.0 to Heroku users via the Cloudant add-on. Cloudant is a distributed CouchDB service, with the added benifits of data redundancy, clustering, and automatic maintenance (view builds and compaciton). You can use it just like you would standalone CouchDB but you have the advantage of your data being distributed over multiple machines. The following is a (very short) guide to help you get started with Cloudant and Heroku. It is by no means comprehensive. If you have quesitons, feel free to get in touch. You can read more about the add-on at the Heroku Blog.

Local setup

Since CouchDB and Cloudant have the same REST API you can use them the same way. You just need a http client to interface with the database and a JSON parser.

In the simplest case you can just use the rest-client and json gems:

$ sudo gem install rest-client json

If you don’t already have CouchDB on your local machine:

OSX:

$ brew install couchdb

Ubuntu:

$ sudo apt-get install couchdb

Further reading:

Using from Sinatra

Installing the Cloudant add-on gives you an environmental variable CLOUDANT_URL. This contains your API URL and credentials and is how you access your database(s) at Cloudant:

$ heroku config --long CLOUDANT_URL
https://USER:PASSWORD@APP.heroku.cloudant.com

When you first install the add-on you need to create a database:

Using cURL:

$ curl -X PUT https://USER:PASSWORD@APP.heroku.cloudant.com/DATABASENAME

Using rest-client:

$ RestClient.put("https://USER:PASSWORD@APP.heroku.cloudant.com/DATABASENAME", "")

You could also do this in your code by doing something like:

begin
  RestClient.put("#{ENV['CLOUDANT_URL']}/SOMEDATABASE", "")
rescue
  puts "database already created"
end

The following code will allow you to GET a document from the music database and then print it to the page:

DB = "#{ENV['CLOUDANT_URL']}/music"
get "/doc/:doc" do
  doc = RestClient.get("#{DB}/#{params[:doc]}")
  @result = JSON.parse(doc)
  haml :doc_id
end

The view would look something like:

%h1 A Doc from CouchDB!
- @result.each do |k,v|
  %b=k
  %em=v
  %br

To request this page by pointing your browser to:

http://SOMEAPP.heroku.com/doc/YOURDOCUMENT

Deploying to Heroku

To use Cloudant on Heroku, install the Cloudant add-on:

$ heroku addons:add cloudant:basic