Search code examples
httpwolfram-mathematicacouchdb

Insert document into CouchDB using Mathematica


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?


Solution

  • 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]