Kapil
Kapil

Reputation: 423

Using OCaml cohttp Client.post method

I'm trying to use the OCaml cohttp package to send a POST request using the Client.post method. I looked at the example in ocaml-cohttp/lib_test/test_net_lwt_client_and_server.ml to use the method, here's a code snippet from the example which uses the function.

Client.post ~body:(Cohttp_lwt_body.of_string "barfoo") url

I'm using the function exactly the same way in my own code:

Client.post ~body:(Cohttp_lwt_body.of_string bodyString) (Uri.of_string stringURI) >>= function
                            | Some (_, body) -> Cohttp_lwt_body.string_of_body body
                            | None -> return ""

But I get the error message:

Error: This pattern matches values of type 'a option
   but a pattern was expected which matches values of type
     Cohttp.Response.t * Cohttp_lwt_body.t

I looked at https://github.com/mirage/ocaml-cohttp/issues/64 which suggested changing the ~body label to ?body but then I got a different error:

Error: This expression has type Cohttp_lwt_body.t
   but an expression was expected of type Cohttp_lwt_body.t option

Could someone please explain how to use this function correctly?

Upvotes: 1

Views: 728

Answers (1)

hcarty
hcarty

Reputation: 1671

The error message indicates that this is a typing issue:

Error: This pattern matches values of type 'a option
   but a pattern was expected which matches values of type
     Cohttp.Response.t * Cohttp_lwt_body.t

Your function body to the right of the bind (>>=) should be rewritten to handle the tuple returned by Client.post rather than an option type. For example:

Client.post
  ~body:(Cohttp_lwt_body.of_string bodyString)
  (Uri.of_string stringURI)
>>= fun (response, body) ->
match response with
| { Cohttp.Response.status = `OK; _ } -> ok_response_action body
| { Cohttp.Response.status; _ } -> other_response_action status body

cohttp does not, unfortunately, currently have easily accessible documentation. You would need to reference the .mli files from the source directly. For example, see here for information on the Cohttp.Response.t type's structure.

Upvotes: 2

Related Questions