Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best module for HttpRequest in OCaml

I wish to use OCaml to access the Yahoo Finance API. Essentially, it will be just a bunch of HTTP requests to get quotes from Yahoo Finance.

Which module I should use?

I wish to have async HTTP requests.

like image 726
Jackson Tale Avatar asked Jan 03 '13 06:01

Jackson Tale


2 Answers

Just for the record, there is also ocurl with curl multi API support.

like image 43
ygrek Avatar answered Oct 01 '22 18:10

ygrek


There are possibilities using lwt:

  • ocsigen has a quite complete and a bit complex implementation
  • cohttp is a bit simpler but lacks some usefull parts

using opam to install:

$ opam install ocsigenserver cohttp

For instance in a toplevel:

try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH") with _ -> ();;
#use "topfind";;
#thread;;
#require "ocsigenserver";;
open Lwt

(* a simple function to access the content of the response *)
let content = function
  | { Ocsigen_http_frame.frame_content = Some v } ->
      Ocsigen_stream.string_of_stream 100000 (Ocsigen_stream.get v)
  | _ -> return ""

(* launch both requests in parallel *)
let t = Lwt_list.map_p Ocsigen_http_client.get_url
  [ "http://ocsigen.org/";
    "http://stackoverflow.com/" ]

(* maps the result through the content function *)
let t2 = t >>= Lwt_list.map_p content

(* launch the event loop *)
let result = Lwt_main.run t2

and using cohttp:

try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH") with _ -> ();;
#use "topfind";;
#require "cohttp.lwt";;
open Lwt

(* a simple function to access the content of the response *)
let content = function
  | Some (_, body) -> Cohttp_lwt_unix.Body.string_of_body body
  | _ -> return ""

(* launch both requests in parallel *)
let t = Lwt_list.map_p Cohttp_lwt_unix.Client.get
  (List.map Uri.of_string
     [ "http://example.org/";
       "http://example2.org/" ])

(* maps the result through the content function *)
let t2 = t >>= Lwt_list.map_p content

(* launch the event loop *)
let v = Lwt_main.run t2

Notice that an implementation of cohttp for jane street async library is also available

like image 183
Pierre Chambart Avatar answered Oct 01 '22 18:10

Pierre Chambart