Cohttp ia a lightweight HTTP client/server library. Its interface is simple and easy to use. This library is useful for web scraping and requesting to API servers. In this example, we obtain a description of a given word from the DuckDuckGo API.
In [1]:
#require "cohttp,cohttp-lwt-unix,ppx_deriving_yojson" ;;
In [2]:
open Lwt.Infix ;;
In [3]:
type t = {
definition : string [@key "Definition"];
abstract : string [@key "Abstract"];
} [@@deriving yojson { strict = false }]
Out[3]:
In [4]:
let query = "OCaml" (* Search query *)
let body =
Lwt_main.run begin
let base_uri = Uri.of_string "http://api.duckduckgo.com/?format=json" in
let uri = Uri.add_query_param base_uri ("q", [query]) in
Cohttp_lwt_unix.Client.get uri >>= fun (resp, body) -> (* GET contents from a given uri *)
assert (Cohttp.Response.status resp = `OK) ; (* Check HTTP response code *)
Cohttp_lwt_body.to_string body >|= fun body -> (* Receive contents *)
Yojson.Safe.from_string body
|> [%of_yojson: t]
|> function
| Result.Ok { definition = ""; abstract = ""; } -> None
| Result.Ok { definition = ""; abstract; } -> Some abstract
| Result.Ok { definition; abstract = ""; } -> Some definition
| _ -> failwith "Oops!"
end
Out[4]:
Out[4]:
In [ ]: