GithubHelp home page GithubHelp logo

roar's Introduction

ROAR

Streamlines the development of RESTful, Resource-Oriented Architectures in Ruby.

Introduction

Roar is a framework for developing distributed applications while using hypermedia as key for application workflow.

REST is an architectural style for distributed systems. However, many implementations forget about the distributed part of REST and simply map CRUD operations to HTTP verbs in a monolithic application.

Features

  • Roar worries about incoming and outgoing representation documents.
  • Representers let you declaratively define your representations.
  • Representations now are OOP instances with accessors, methods and behaviour.
  • Both rendering and parsing representations is handled by representers which keeps knowledge in one place.
  • Features as hypermedia support and HTTP methods can be mixed in dynamically.
  • Representers are packagable in gems for distribution to services and clients.
  • Framework agnostic, runs with Sinatra, Rails & Co.
  • Extra support for Rails.
  • Makes testing distributed REST systems as easy as possible.

Example

Say your webshop consists of two completely separated apps. The REST backend, a Sinatra app, serves articles and processes orders. The frontend, being browsed by your clients, is a rich Rails application. It queries the services for articles, renders them nicely and reads or writes orders with REST calls. That being said, the frontend turns out to be a pure REST client.

Representations

Representations are the pivotal elements of REST. Work in a REST system means working with representations, which can be put down to parsing or extracting representations and rendering the like.

Roar makes it easy to render and parse representations of resources after defining the formats.

Creating Representations

Why not GET a particular article, what about a good beer?

GET http://articles/lonestarbeer

It’s cheap and it’s good. The response of a GET is a representation of the requested resource. A representation is always a document. In this example, it’s a bit of JSON.

{ "article": {
  "title":  "Lonestar Beer",
  "id":     4711,
  "links":[
    { "rel":  "self", 
      "href": "http://articles/lonestarbeer"}
  ]}
}

In addition to boring article data, there’s a link embedded in the document. This is hypermedia, yeah! We will learn more about that shortly.

So, how did the service render that JSON document? It could use an ERB template, #to_json, or maybe another gem. The document could also be created by a representer.

Representers are the key ingredience in Roar, so let’s check them out!

Representers

To render a representational document, the backend service has to define a representer.

module JSON
  class Article
    include Roar::Representer::JSON
    
    property :title
    property :id
    
    link :self do
      article_url(represented)
    end 
  end
end

Hooray, we can define plain properties and embedd links easily – and we can even use URL helpers (in Rails). There’s even more, nesting, collections, but more on that later!

Rendering Representations in the Service

In order to render an actual document, the backend service would have to do a few steps: creating a representer, filling in data, and then serialize it.

JSON::Article.new(
  :title  => "Lonestar",
  :id     => 666).
  serialize # => "{\"article\":{\"id\":666, ...

Using the ModelRepresenting feature module we can take a shortcut.

@beer = Article.find_by_title("Lonestar")

JSON::Article.from_model(@beer).
  serialize # => "{\"article\":{\"id\":666, ...

Articles itself are useless, so they may be placed into orders. This is the next example.

Nesting Representations

What if we wanted to check an existing order? We’d GET http://orders/1, right?

{ "order": {
  "id":         1,
  "client_id":  "815",
  "articles":   [
    {"title": "Lonestar Beer",
    "id":     666,
    "links":[
      { "rel":  "self", 
        "href": "http://articles/lonestarbeer"}
    ]}
  ],
  "links":[
    { "rel":  "self", 
      "href": "http://orders/1"},
    { "rel":  "items", 
      "href": "http://orders/1/items"}
  ]}
}

Since orders may contain a composition of articles, how would the order service define its representer?

module JSON
  class Order 
    include Roar::Representer::JSON
    
    property :id
    property :client_id
    
    collection :articles, :as => Article
    
    link :self do
      order_url(represented)
    end
    
    link :items do
      items_url
    end 
  end
end

The declarative #collection method lets us define compositions of representers.

Parsing Documents in the Service

Rendering stuff is easy: Representers allow defining the layout and serializing documents for us. However, representers can do more. They work bi-directional in terms of rendering outgoing and parsing incoming representation documents.

If we were to implement an endpoint for creating new orders, we’d allow POST to http://orders/. Let’s explore the service code for parsing and creation.

  post "/orders" do
    incoming = JSON::Order.deserialize(request.body.string)
    puts incoming.to_attributes #=> {:client_id => 815}

Again, the ModelRepresenting module comes in handy for creating a new database record.

  post "/orders" do
    # ...
    @order = Order.create(incoming.to_nested_attributes)
    
    JSON::Order.for_model(@order).serialize

Look how the #to_nested_attributes method helps extracting data from the incoming document and, again, #serialize returns the freshly created order’s representation. Roar’s representers are truely working in both directions, rendering and parsing and thus prevent you from redundant knowledge sharing.

Representers in the Client

The new representer abstraction layer seems complex and irritating first, where you used params[] and #to_json is a new OOP instance now. But… the cool thing is: You can package representers in gems and distribute them to your client layer as well. In our example, the web frontend can take advantage of the representers, too.

Using HTTP

Communication between REST clients and services happens via HTTP – clients request, services respond. There are plenty of great gems helping out, namely Restfulie, HTTParty, etc. Representers in Roar provide support for HTTP as well, given you mix in the HTTPVerbs feature module!

To create a new order, the frontend needs to POST to the REST backend. Here’s how this could happen using a representer on HTTP.

  order = JSON::Order.new(:client_id => current_user.id)
  order.post!("http://orders/")

A couple of noteworthy steps happen here.

  1. Using the constructor a blank order document is created.
  2. Initial values like the client’s id are passed as arguments and placed in the document.
  3. The filled-out document is POSTed to the given URL.
  4. The backend service creates an actual order record and sends back the representation.
  5. In the #post! call, the returned document is parsed and attributes in the representer instance are updated accordingly,

After the HTTP roundtrip, the order instance keeps all the information we need for proceeding the ordering workflow.

  order.id #=> 42

Discovering Hypermedia

Now that we got a fresh order, let’s place some items! The system’s API allows adding articles to an existing order by POSTing articles to a specific resource. This endpoint is propagated in the order document using hypermedia.

Where and what is this hypermedia?

First, check the JSON document we get back from the POST.

{ "order": {
  "id":         42,
  "client_id":  1337,
  "articles":   [],
  "links":[
    { "rel":  "self", 
      "href": "http://orders/42"},
    { "rel":  "items", 
      "href": "http://orders/42/items"}
  ]}
}

Two hypermedia links are embedded in this representation, both feature a rel attribute for defining a link semantic – a “meaning” – and a href attribute for a network address. Isn’t that great?

  • The self link refers to the actual resource. It’s a REST best practice and representations should always refer to their resource address.
  • The items link is what we want. The address http://orders/42/items is what we have to refer to when adding articles to this order. Why? Cause we decided that!

Using Hypermedia

Let the frontend add the delicious “Lonestar” beer to our order, now!

beer = JSON::Article.new(:title => "Lonestar Beer")
beer.post(order.links[:items])

That’s all we need to do.

  1. First, we create an appropriate article representation.
  2. Then, the #links method helps extracting the items link URL from the order document.
  3. A simple POST to the respective address places the item in the order.

The order instance in the frontend is now stale – it doesn’t contain articles, yet, since it is still the document from the first post to http://orders/.

order.items #=> []

To update attributes, a GET is needed.

order.get!(order.links[:self])

Again, we use hypermedia to retrieve the order’s URL. And now, the added article is included in the order.

Note: If this looks clumsy – It’s just the raw API for representers. You might be interested in the upcoming DSL that simplifys frequent workflows as updating a representer.]

order.to_attributes #=> {:id => 42, :client_id => 1337, 
  :articles => [{:title => "Lonestar Beer", :id => 666}]}

This is cool, we used REST representers and hypermedia to create an order and fill it with articles. It’s time for a beer, isn’t it?

Using Accessors

What if the ordering API is going a different way? What if we had to place articles into the order document ourselves, and then PUT this representation to http://orders/42? No problem with representers!

Here’s what could happen in the frontend.

beer = JSON::Article.new(:title => "Lonestar Beer")
order.items << beer
order.post!(order.links[:self])

This was dead simple since representations can be composed of different documents in Roar.

Current Status

Please note that Roar is still in conception, the API might change as well as concepts do.

What is REST about?

Making that system RESTful basically means

  1. The frontend knows one single entry point URL to the REST services. This is http://orders.
  2. Do not let the frontend compute any URLs to further actions.
  3. Showing articles, creating a new order, adding articles to it and finally placing the order – this all requires further URLs. These URLs are embedded as hypermedia in the representations sent by the REST backend.

roar's People

Contributors

apotonick avatar gregkare avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.