Skip to content

Adding a resource from scratch without scaffold

Andreas Fast edited this page May 22, 2014 · 4 revisions

The Goal

The goal is to show all the steps involved while adding a new resource and an action for that resource.

Files you need to look at (example: comment)

  • Register the comments in services/my_awesome_api.rb
  • Create the resource class at resources/comments.rb
  • Create the definitions/comments/ directory.
  • Create the definitions/comments/operations.yml file.
  • Add the new action to the operations.yml and comments.rb files.

Registering the resource

services/my_awesome_api.rb

class MyAwesomeApi < Angus::Base
  def configure
    register :posts
    register :comments
  end
end

Creating the new resource class and adding a new action

resources/comments.rb

class Comments < Angus::BaseResource
  def index
    comments = [{
      :id => 1,
      :content => "My first comment!"
    }]
    { :comments => comments }
  end
end

Creating the operations.yml file and adding the corresponding action

definitions/comments/operations.yml

index:
  name: 'index'
  description: 'Get all comments.'
  path: '/comments'
  method: 'get'

  response:
    - element: 'comments'
      description: 'The array of comments'
      required: true
      elements_type: comment

Notice how the response element matches the keys returned by the hash in the resource! And how the type matches the value for that key.

Creating the required representation

definitions/representations.yml

comment:
  - field: id
    description: The comment id.
    type: integer
    required: true
  - field: content
    description: The comment.
    type: string
    required: true

Trying it out!

Now run angus server in the root of your project. It should start the server and if you go to http://localhost:9292/ (9292 is the default port) you will see something like this:

{"doc":"/awesome/doc/0.1","api":"/awesome/api/0.1"}

At http://localhost:9292/awesome/doc/0.1/ you will find the autogenerated documentation for your api. And if you go to http://localhost:9292/awesome/api/0.1/ you will probably get a RouteNotFound error. But it's still the base for out api, to get to comments we need to append that path so it looks like

http://localhost:9292/awesome/api/0.1/comments

and we get a success response:

{"status":"success","comments":[{"id":1,"content":"My first comment!"}]}