I have been working a project to create a REST web service for testing purposes. Since I work for a company that uses Ruby and MongoDB that’s what I decided to use. Turns out the hard part wasn’t making Sinatra talk to the Mongo database, but was figuring out how to take the results and convert to a JSON format.
The ruby code is pretty simple, you have 5 required gems to install and 6 lines of code
!#/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
require 'haml'
require 'mongo'
require 'json'
DB = Mongo::Connection.new.db("local")
coll = DB.collection('skip')
get '/api/user/:val.json' do
content_type "application/json"
docs = coll.find({"id" => Integer(params[:val]), "type" => "user"}, :fields => {:_id => 0}).to_a
test = Hash[*docs]
test.to_json
end
I have looking up the user data by there ID which is passed in the URL and captured by :val This is passed as a search parameter to the MongoDB find along with the “type” which in this case is user. I don’t want the id created by MongoDB in the requests so I set the field to false in the return by setting :fields => {:_id => 0}. What you get back from MongoDB is BSON which look a lot like JSON in the MongoDB console, but it’s not! If you don’t take the results and convert them to a array using .to_a then you will get the database cursor value. There are couple more steps to take to massage the data into something for people to use. The array has to be turned into a ruby hash Hash[*whatever] (looks a lot like a C pointer). Then the hash can be turned into a JSON string using .to_json


