View on GitHub

Toast Manual

Toast is a Rack application that hooks into Ruby on Rails. It exposes ActiveRecord models as a web service (REST API).

Version 1.0.*

Table of Contents - Directives

Directive ‘via_post’

via_post { ... }

The directive activates the routing of POST requests to the application. POST requests send JSON data in order to create new resources/model-instances on the server and return the created resource.

via_post may appear inside the directives:

The directive’s block contains allow (required) and handler directives (optional), which define run-time code to decide on authorization and contain custom business logic if the built-in default handlers are not appropriate.

To create new resources the POST request’s URI must specify the base resource under which the new resource shall be available. This can be either the :all collection or a plural association.

Example

expose(Person) {
  readables :first_name, :last_name
  collection(:all) {
    via_get {
      allow do |*args|
        true
      end
    }

    via_post {
      allow do |*args|
        true
      end

      ## implicit handler
      # handler do |payload, uri_params|
      #   Person.create! payload
      # end
    }
  }

  association(:posts) {
    via_get {
      allow do |*args|
        true
      end
    }

    via_post {
      allow do |*args|
        true
      end

      ## Implicit handler
      # handler do |person, payload, uri_params|
      #   person.posts.create! payload
      # end
    }
  }
}

expose(Post) {
  readables :title, :text
  via_get {
    allow do |*args|
      true
    end
  }

  association(:author) {
    via_get {
      allow do |*args|
        true
      end
    }
  }
}

Request:

POST https://example.com/people
  {"first_name": "Elinor", "last_name": "Langosh"}

Response:

{
    "self"      : "https://example.com/people/102",
    "posts"     : "https://example.com/people/102/posts",
    "first_name": "Elinor",
    "last_name" : "Langosh"
}

Request:

POST https://example.com/people/102/posts
  {"title": "My First Toast", "text": "It was a bit dry."}

Response:

{
    "self"      : "https://example.com/posts/2957",
    "author"    : "https://example.com/posts/2957/author",
    "title"     : "My First Toast",
    "text"      : "It was a bit dry."
}