package routes

  1. Overview
  2. Docs
Legend:
Library
Module
Module type
Parameter
Class
Class type

Routes

Introduction

Routes is a routing library for OCaml that allows defining type safe routes, to dispatch a request to a matching handler, based on path parameters in the input URI target. Type safe in this context, refers to processing the input URI in a manner that assigns concrete types to the values extracted from the path parameters.

The library has no external dependencies aside from the OCaml standard library, and it can be used in both native (via ocamlopt) and javascript usecases (via js_of_ocaml). It isn't tied to any particular framework, with the intention for frameworks to provide a higher level wrapper around it.

Installation

Routes is published on the opam repository. If using opam, install it via

stable version:

opam install routes 

development version:

opam pin add routes.dev git+https://github.com/anuragsoni/routes.git 

If using esy, add the dependency @opam/routes to package.json/esy.json. Or you can use esy add @opam/routes to add it to the manifest file automatically.

Usage

let greet_user (name : string) (id : int) =
  Printf.sprintf "Hello, %s [%d]" name id

let add_user (name : string) (id : int) (is_admin : bool) =
  Printf.sprintf "Added user %s with id %d. IsAdmin? %b" name id is_admin

let greet_user_route () = Routes.(s "user" / str / int /? nil)
let add_user_route () = Routes.(s "user" / str / int / bool / s "add" /? nil)

let router = Routes.one_of [ greet_user_route () @--> greet_user
                           ; add_user_route () @--> add_user ]

Routes ships with patterns that match the following types: int, int32, int64, bool, string, but it is possible to define custom patterns that can be used to extract path parameters that can be parsed into a user defined type.

type shape =
  | Square
  | Circle

let shape_of_string = function
  | "square" -> Some Square
  | "circle" -> Some Circle
  | _ -> None

let shape_to_string = function
  | Square -> "square"
  | Circle -> "circle"

let shape = Routes.pattern shape_to_string shape_of_string

(* Now the shape pattern can be used just like any
   of the built in patterns like int, bool etc *)
let route () = s "shape" / shape / s "create" /? nil

Support

Routes' git repository is located on Github. Use the repository's issue tracker to file bug reports and feature requests.

License

Routes is distributed under the BSD-3-clause license.

API documentation

  • Routes Typed routing for OCaml. Routes provides combinators for adding typed routing to OCaml applications. The core library will be independent of any particular web framework or runtime.