Note: This content was migrated from the old MoinMoin wiki and may be out of date (last modified: 2011)
Getting started with OCaml and the CouchDB API
For making the HTTP calls required by the RESTful API, it's hard to beat Gerd Stolpmann's Http_client.Convenience module (see http://docs.camlcity.org/docs/godipkg/3.11/godi-ocamlnet/doc/godi-ocamlnet/html/Http_client.Convenience.html ), shipped with the ocamlnet-2 library (see http://docs.camlcity.org/docs/godipkg/3.11/godi-ocamlnet ). The examples below assume your database is running on the localhost, port 5984--and that your database is named "mydatabase". Naturally, you're encouraged to change these to fit your specific needs.
Creating a Database
let result = let server_url = "http://localhost:5984" in let db_name = "mydatabase" in Http_client.Convenience.http_put (server_url ^ "/" ^ db_name) "";; print_endline result
Deleting a Database
let result = let server_url = "http://localhost:5984" in let db_name = "mydatabase" in Http_client.Convenience.http_delete (server_url ^ "/" ^ db_name);; print_endline result
Creating a Document
let result = let url_doc = "http://localhost:5984/mydatabase/newdoc" in let my_doc_json = "{ \"subject\":\"Plankton\", \"author\":\"Rusty\"," ^ "\"body\":\"I decided today I like plankton and OCaml equally well.\" }" in Http_client.Convenience.http_put url_doc my_doc_json;; print_endline result
Retrieving a Document
The example below shows a bit more sophistication, illustrating how to use the json-wheel library (located at http://martin.jambon.free.fr/json-wheel.html).
type json doc = < subject:string; author:string; body:string > let url_doc = "http://localhost:5984/mydatabase/newdoc" let get url = doc_of_json (Json_io.json_of_string (Http_client.Convenience.http_get (url))) let my_doc = (get url_doc) let _= print_string ("Author: " ^ my_doc#author ^ "\n" ^ "Subject: " ^ my_doc#subject ^ "\n" ^ "Body: " ^ my_doc#body ^ "\n") $ ./retrieve_doc Author: Rusty Subject: Plankton Body: I decided today I like plankton and OCaml equally well.
Note: These examples can be compiled with the following:
ocamlfind ocamlopt -o dest-file -linkpkg -package json-static,netclient -syntax camlp4o source-file.ml