PlugRest: resource behaviour and router for hypermedia web apps

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:

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}

  def content_types_provided(conn, state) do
    {[{"text/html", :to_html}], conn, state}

  def to_html(conn, state) do
    {"Hello #{state}", conn, state}

And a Router in Plug:

defmodule MyApp.Router do
  use PlugRest.Router

  plug :match
  plug :dispatch

  resource "/hello", MyApp.HelloResource, "World"

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.


Nice, looks to be quite useful.

This post by Sean Cribbs is what first piqued my interest in Webmachine:

1 Like