christopheradams
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:
-
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.
Most Liked
christopheradams
This post by Sean Cribbs is what first piqued my interest in Webmachine: Webmachine vs. Grape - Sean Cribbs
Popular in Announcing
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








