Tutorial for Cohttp-lwt as API client

It’s two years later, so I thought I’d drop a note with great detailer for the next passer by for what worked well for me.

  • atdgen is neat, but by default in their demo/instructions serializes your JSON to a binary format, requires Biniou (not optional, even though the instructions don’t suggest as much), and Biniou is not maintained.
  • yojson seems to be active and the the hip thing. i installed yojson and ppx_deriving_yojson

Draft your type:

(* MySweetData.ml *)
type my_sweet_data = {
  a: int;
  b: string;
} [@@deriving yojson];;
(* im actually in an ocaml/reason hybrid project, wasn't sure how to do this in reason syntax *)

Configure your build to support the ppx:

(library
 (name lib)
 ...
 (preprocess (pps ppx_deriving_yojson))

Then some nice serialization/deserialization functions just show up conveniently:

MySweetData.my_sweet_data_of_yojson (* deserialize *)
MySweetData.my_sweet_data_to_yojson (* serialize *)

(* ... *)

MySweetData.my_sweet_data_of_yojson (Yojson.Safe.from_string some_json)

Donzo.

1 Like