How to post from mathematica to rails application using json.

A mathematica package is available for this at github railsmath This package has support for posting json to ruby on rails and pulling active record models from rails into mathematica. It uses associations and rules to post the data. For index queries it returns a list that can be manipulated

The package is used reasonably extensively in my code so the basics should be working. Post and get an individual model is nicely working. Getting all models is not as nice as it returns a list rather than an association of associations.

Detailed process how railsmath package above was developed

This was a three hour hit and miss session to get working so I thought i would share it.

Using curl


curl  -H "Content-type: application/json" -X "POST" -d '{"net_asset_value":{"accountname":"scott","nav":24}}' ""

The documentation for URLFetch was not exactly helpful. (eg parameters versus body for a post message either seems correct). However create some rules to represent the data you want to post. Assign it to the body with the correct headers and send it. (Note the conversion of the rules to json usng ExportString)

Mathematic code


rules = "net_asset_value" -> {"accountname" -> "scott", "nav" -> 24 }
res = URLFetch[url,  "Body" -> ExportString[{rules}, "JSON"], 
  "Method" -> "POST", 
  "Headers" -> {"Content-type" -> "application/json"}]