Skip to content

Instantly share code, notes, and snippets.

@dudelson
Created June 19, 2017 20:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dudelson/4b418e09c66c9d872d1fa81d7a0b20e9 to your computer and use it in GitHub Desktop.
Save dudelson/4b418e09c66c9d872d1fa81d7a0b20e9 to your computer and use it in GitHub Desktop.
A minimal example of how to use ocaml-webmachine to build a REST API. This API returns HTTP error 406 ("Not Acceptable") for every valid request
(** Returns http error 406 for every valid request.
build with: `ocamlbuild -use-ocamlfind -pkgs cohttp.lwt,lwt,webmachine main.byte` *)
open Cohttp
open Cohttp_lwt_unix
open Lwt.Infix
module Wm = struct
include Webmachine.Make(Cohttp_lwt_unix_io)
module Rd = Webmachine.Rd
end
class handler = object(self)
inherit [Cohttp_lwt_body.t] Wm.resource
method content_types_accepted rd = Wm.continue [] rd
method content_types_provided rd = Wm.continue [] rd
end
let main () =
let routes = [
("/foo", fun () -> new handler);
("/bar/:id", fun() -> new handler);
] in
let callback _conn request body =
Wm.dispatch' routes body request >|= (function
| Some r -> r
| None -> (`Not_found, Header.init (), `String "Nope sorry", []))
>>= (fun (status, headers, body, path) ->
Server.respond ~status ~headers ~body ()) in
Server.create ~mode:(`TCP (`Port 8081)) (Server.make ~callback ())
let () = Lwt_main.run(main ())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment