This example defines a simple HTTP server that listens on port 8000 and responds to two types of requests:
- If a client sends a GET request to the path “/hello”, the server will respond with a status code of 200 and a body of “Hello, World!“.
- If the client sends a request to any other path, the server will respond with a status code of 404 (Not Found).
This is a very simple example, but it should give you an idea of how to create a REST API using OCaml and the **Cohttp** and **Lwt** libraries.
open Lwt.Infix
open Cohttp
open Cohttp_lwt_unix
let server =
let callback _conn req body =
let path = Uri.path (Request.uri req) in
let response =
match path with
| "/hello" ->
let body = "Hello, World!" in
Server.respond_string ~status:`OK ~body ()
| _ -> Server.respond_not_found ()
in
body |> Cohttp_lwt.Body.drain >>= fun () -> response
in
Server.create ~mode:(`TCP (`Port 8000)) (Server.make ~callback ())
let () = Lwt_main.run serverIn the example I provided, **callback** is a function that takes three arguments: **_conn**, **req**, and **body**. These arguments are usually separated by spaces and have the same indentation level.
The **_** before the **conn** argument is a convention to indicate that this argument will not be used in the function. This is similar to using a variable with a single leading underscore in other languages.
The **let** keyword is used to define a variable or a function, like in other programming languages. In this example, **callback** is a function and the three arguments (**_conn**, **req**, and **body**) are variables.
Also, In OCaml the parentheses are optional for function calls. That means that the following two expressions are equivalent:
function_name arg1 arg2 arg3
function_name(arg1, arg2, arg3)