Couchrest: RESTful Ruby Client for CouchDB

Couchrest: RESTful Ruby Client for CouchDB
By jchris in Coding 3 months ago.

In my last post, I convinced you that you want to use CouchDB for your next project, and of course you already love Ruby, so by now you’re curious about Couchrest, my simple Ruby CouchDB client library.

Examples First

Specify a server:

server = CouchRest.new("http://localhost:5984")

Create a database:

db = server.create_db('my-db')

Create a document with id specified (just leave the _id off and CouchDB will assign a unique one for you):

db.save({'_id' => 'my-doc', 'will-exist' => 'here'})

Fetch a document by id:

doc = db.get('my-doc'); doc['will-exist'] #=> 'here'

Delete the document:

db.delete(doc)

There much more example code (including view creation and queries) in the RSpec files, but the best thing to do is just play with it.

Other options?

There are already a few other Ruby clients for CouchDB: CouchObject is notable for providing some smart serializations of Ruby objects into JSON-based documents for CouchDB, as well as document lifecycle callbacks. Ruby-CouchDB boasts the ability to do SQL-style queries against the views it creates (maybe it’s still tied to the old old XML version of CouchDB – let me know if I’m wrong). ActiveCouch gives an ActiveRecord style interface to your documents, allowing you to specify types, callbacks, and even migrations.

Why Couchrest? Less Code!

Couchrest is a loose port of couch.js part of CouchDB’s Futon admin interface, which I found to be concise, clear, and well designed.

I prefer to stay close to the metal, especially when the metal is as clean and simple as CouchDB’s HTTP API. The only thing Couchrest does for you is manage the Ruby <=> JSON serialization, and point your actions (database creation, document CRUD, view creation and queries, etc) at the appropriate API endpoints. There’s no bonus points for storing your docs in a special format, and nothing that will tie you to Ruby or my library as a platform. Want to move over to Python or Javascript for your backend? Easy, no big changes to make.

The core of Couchrest is Heroku’s excellent REST Client Ruby HTTP wrapper. REST Client takes all the nastyness of Net::HTTP and gives is a pretty face, while still giving you more control than Open-URI. I recommend it anytime you’re interfacing with a well-defined API. (We use it for Grabb.it’s Tumblr integration, and it works like a charm.)

Enjoy!

Be the first to comment on Couchrest: RESTful Ruby Client for CouchDB

Post a comment