Just began with Reason and OCaml today. I've started with the https://github.com/esy-ocaml/hello-reason sample. I want to make a HTTP API call so I've installed ocaml-cohttp with: esy add @opam/cohttp-lwt
.
Now I want to use that library (or any that you may have as a suggestion) within the hello-reason getting started sample.
I can't find reference documentation on how to import it. I've tried:
open cohttp-lwt
Can I use OCaml libraries within in Reason code files?
Yes, the only difference is syntax. The client tutorial can be translated directly, and automatically into this:
open Lwt;
open Cohttp;
open Cohttp_lwt_unix;
let body =
Client.get(Uri.of_string("https://www.reddit.com/"))
>>= (
((resp, body)) => {
let code = resp |> Response.status |> Code.code_of_status;
Printf.printf("Response code: %d\n", code);
Printf.printf(
"Headers: %s\n",
resp |> Response.headers |> Header.to_string,
);
body
|> Cohttp_lwt.Body.to_string
>|= (
body => {
Printf.printf("Body of length: %d\n", String.length(body));
body;
}
);
}
);
let () = {
let body = Lwt_main.run(body);
print_endline("Received body\n" ++ body);
};
Edit: hello-reason
uses ocaml-dune, so you also have to add cohttp-lwt-unix
to the libraries
stanza in the project's dune
file, as shown in the client tutorial here.