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
confusion.

From the browser, just post the JSON – I’m using the JollyToad library
for $.toJSON (http://jollytoad.googlepages.com/json.js):

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

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

post ‘/sessions’ do
session = JSON.parse(request.body.read.to_s)

end

(The hard part was working out how to get the raw data, i.e.
request.body.read, and then realising it’s not actually a string.
There are a few variants such as request.POST – see also
http://www.gittr.com/index.php/archive/getting-data-into-a-sinatra-application/)

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: