Adding basic authentication to Cohttp_lwt_unix example

Hi, Im struggling to work out the method to add authentication to a Client.get in the Cohttp_lwt_unix package. Got this far, but cant work out what’s wrong:

open Lwt
open Cohttp
open Cohttp_lwt_unix

let body = 
  let headers = Header.init () 
  |> fun h -> Header.add h "content-type" "application/json" 
  |> fun h -> Header.add_authorization h ("username", "password") in
  Client.get ~headers (Uri.of_string "https://www.reddit.com/") >>= fun (resp, body) ->
  let code = resp |> Response.status |> Code.code_of_status in
  Printf.printf "Response code: %d\n" code;
  Printf.printf "Headers: %s\n" (resp |> Response.headers |> Header.to_string);
  body |> Cohttp_lwt.Body.to_string >|= fun body ->
  Printf.printf "Body of length: %d\n" (String.length body);
  body

let () =
  
  let body = Lwt_main.run body in
  print_endline ("Received body\n" ^ body)
1 Like

It’s difficult to say it you don’t tell us what the problem is.

1 Like

So in the line where I add the credentials it isn’t happy with the syntax
|> fun h → Header.add_authorization h (“username”, “password”) in
type credentials has 2 forms Basic string * string and Other.

It helps if you give us the error messages and links to the docs. But I bet you have to do something like:

 (`Basic ("username", "password"))

Yes I was missing the `Basic was all. I though the compiler would have inferred the type. Sorry to bother you again Daniel. Thanks very much, Ian.

Not bothered! I wouldn’t respond if I was :–)

The compiler infers types, not values which is what you have to write here.

2 Likes