I’ve long been a fan of REST-based systems such as Webmachine and later cowboy_rest for writing web apps in Erlang.
If you’re not familiar with the concept: instead of building routes with “verb/path/controller/action” like we do in Phoenix, we match a URL path with a module that describes our resource declaratively using callbacks like resource_exists
, content_types_accepted
, etc. The module is handed to a state machine that executes over these functions and constructs a response.
If you’ve never used one of these libraries, you owe it to yourself to try it out. You’ll learn a lot about good HTTP semantics!
Anyway, I wanted to have this same behavior available in Plug and Phoenix, so I translated the core of cowboy_rest into a Plug module, and wrote resource
macros that work in each library’s router. The result is two new hex packages:
-
PlugRest: REST behaviour and Plug router for hypermedia web applications in Elixir
-
PhoenixRest: Resource routing and REST behaviour for Phoenix web applications
Here’s an example of a Resource module:
defmodule MyApp.HelloResource do
use PlugRest.Resource
def allowed_methods(conn, state) do
{["HEAD", "GET", "OPTIONS"], conn, state}
end
def content_types_provided(conn, state) do
{[{"text/html", :to_html}], conn, state}
end
def to_html(conn, state) do
{"Hello #{state}", conn, state}
end
end
And a Router in Plug:
defmodule MyApp.Router do
use PlugRest.Router
plug :match
plug :dispatch
resource "/hello", MyApp.HelloResource, "World"
end
I’ve surely spent as almost much time on the docs as I have on the code, but I know there’s a challenge to understanding webmachine-style frameworks if you’ve never used one.
I’m open to questions, PR’s, and any feedback to help get these libraries to version 1.0.