ocamlocsigen

What's the canonical way to serve JSON using Ocsigen?


The Ocsigen/Eliom tutorial starts with an example of an application that serves up "Hello, world!" as HTML:

open Eliom_content.Html5.D

let main_service =
  Eliom_registration.Html5.register_service
    ~path:["graff"]
    ~get_params:Eliom_parameter.unit
    (fun () () ->
      Lwt.return
         (html
           (head (title (pcdata "Page title")) [])
           (body [h1 [pcdata "Graffiti"]])))

How would one serve this as JSON instead? Specifically, how does one register a JSON service, and what library/combinators should be used to generate/serialize the JSON (js_of_ocaml?)?


Solution

  • I'm not sure to understand what you want to do, but, about JSON, you can use "deriving" (cf. Deriving_Json) to create a JSON type by using an OCaml type like this:

        type deriving_t = (string * string) deriving (Json)
    

    This will create the JSON type corresponding to the OCaml type.

    Here the way of using this type to communicate with the server (if you don't know server functions, here the documentation about it and about client values on server side):

        (* first you have to create a server function (this allowed the client to call a function from the server *)
        let json_call =
          server_function
            Json.t<deriving_t>
            (fun (a,b) ->
               Lwt.return (print_endline ("log on the server: "^a^b)))
    
        (* let say that distillery has already generate all the needed stuff (main_service, Foobar_app, etc..) *)
        let () =
          Foobar_app.register
            ~service:main_service
            (fun () () ->
               {unit{
                 (* here I call my server function by using ocaml types directly, it will be automatically serialize *)
                 ignore (%json_call ("hello", "world"))
               }};
               Lwt.return
                 (Eliom_tools.F.html
                    ~title:"foobar"
                    ~css:[["css";"foobar.css"]]
                    Html5.F.(body [
                       h2 [pcdata "Welcome from Eliom's distillery!"];
                   ])))
    

    If you want to use some client/server communication, you should take a look to Eliom_bus, Eliom_comet or Eliom_react.

    (sorry, I can't make more than 2 links :) but you will find the documentation on the ocsigen.org website).

    Hope that can help you.