Get a description of a word from DuckDuckGo API

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]:
type t = { definition : string; abstract : string; }
val to_yojson : t -> Yojson.Safe.json = <fun>
val of_yojson : Yojson.Safe.json -> t Ppx_deriving_yojson_runtime.error_or =
  <fun>

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]:
val query : string = "OCaml"
Out[4]:
val body : string option =
  Some
   "OCaml, originally named Objective Caml, is the main implementation of the programming language Caml, created by Xavier Leroy, J\195\169r\195\180me Vouillon, Damien Doligez, Didier R\195\169my, Asc\195\161nder Su\195\161rez and others in 1996. A member of the ML language family, OCaml extends the core Caml language with object-oriented programming constructs."

In [ ]: