POSTing JSON to a Sinatra-MongoDB service

30 Dec

I’m using Sinatra and MongoDB, a sensational combo, to build a web
service and wanted to post JSON from the browser. It was easy in the
end, but docs were a little lacking in a couple of places, leading to

From the browser, just post the JSON – I’m using the JollyToad library
for $.toJSON (

$.post(“/sessions”, $.toJSON({
user: $(“#user”).val(),

In the server, I get the JSON payload using
inside a Sinatra rule, and convert it with JSON.

post ‘/sessions’ do
session = JSON.parse(


(The hard part was working out how to get the raw data, i.e., and then realising it’s not actually a string.
There are a few variants such as request.POST – see also


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: