3

I am looking for a way to insert a document into a CouchDB database using Mathematica. Based on this post, I tried it using the following code:

InsertDocument[key_, value_] := 
With[{url = 
  "http://couchdburl/database/"},
Import[url, "XML", "RequestMethod" -> "POST", 
 "RequestParameters" -> {"key" -> key, "value" -> value}]]

But when I try to execute it like this, for instance:

InsertDocument[110, 1]

I get the following error:

Import::erropts: The value {key->110,value->1} specified for the option RequestParameters is invalid. >>

Edit:

Following kguler's comment, I converted the parameters to string, and the previous error disappeared. I have also fixed the forgotten } in my code sample, and removed the concatenation of the url with the key parameter. Now I'm experiencing a different error:

Throw::nocatch: Uncaught Throw[Null,UtilitiesURLToolsPrivateURLTOOLSException[UtilitiesURLToolsPrivateBADCONNECTION,http://couchdburl/database/]] returned to top level. >>

I tried to make a request using curl to the couchDb url, using a dummy document:

curl -X POST http://couchdburl/database/ -H "Content-Type: application/json" -d {}

and the response was as expected:

{"ok":true,"id":"57291ccea74c455beb2d7a37fe001624","rev":"1-967a00dff5e02add41819138abb3284d"}

Am I still missing any option that should be used in the Import function? Maybe some option to set the content-type as application/json?

gdelfino
  • 11,053
  • 6
  • 44
  • 48
mverardo
  • 475
  • 3
  • 9
  • 1
    Did you try making the passed arguments strings (`InsertDocument["100","1"]`) or making the last line in your code `"RequestParameters" -> {"key" -> ToString@key, "value" -> ToString@value}]]`? BTW, you are missing a right brace `}` in the last line. – kglr Jan 18 '12 at 02:47

1 Answers1

1

I managed to do it following the same idea as presented in this SO question.

After some problems, the following code worked:

<< JLink`

client = JavaNew["org.apache.commons.httpclient.HttpClient"];

method = JavaNew["org.apache.commons.httpclient.methods.PostMethod", 
   "http://couchdburl/database/"];

method@setRequestHeader["Content-Type", "application/json"];

entity = 
 JavaNew["org.apache.commons.httpclient.methods.StringRequestEntity", 
  "{\"key\":\"10\",\"value\":\"0\"}", "application/json", Null]

method@setRequestEntity[entity]

client@executeMethod[method]
Community
  • 1
  • 1
mverardo
  • 475
  • 3
  • 9