Skip to content
This repository has been archived by the owner on May 20, 2020. It is now read-only.

scottjacobsen/api-twister

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

API Twister Ruby Gem

What

The api-twister gem is a ruby DSL to define non-trivial APIs.

It works with Rails 2, Rails 3, and without Rails (you will need ActiveSupport, though). It works with ruby 1.9.1 and 1.9.2, and possibly others.

Why

Defining a simple REST API in Rails that returns simple objects is easy. Do it.

However, if you are returning nested objects, want to include methods in your responses, or want to exclude certain attributes, the basic configuration methods can get ugly quickly. Also if you have different serialization options and do not want to use HTTP response codes to describe them (for example, no results were found in a search), things can get ugly. This library hides much of the ugly. It puts knowledge of what attributes, methods, and associations to return in each model class. It allows you to define different named serialization options.

Installation

gem install api-twister

Rails 3:

Add to your Gemfile:

gem 'api-twister'

Rails 2:

Add to your environment.rb:

config.gem 'api-twister'

The Big Picture

  1. Define your API methods in your models using api_define.

  2. Call to_api_json/to_api_xml to serialize your models. These methods use api_hash to build an options hash based on what you defined in your models.

  3. Build sample requests/responses for tests.

  4. Build real requests/responses for controllers and documentation pages.

Show me some code!

class Monkey < ActiveRecord::Base
  has_many :bananas

  include ApiTwister

  define_api do |api|
    api.methods :behavior, :favorite_number, :status
    api.association :bananas
  end

  api :request, :only => [:name]
  api :response                           # default is everything in define_api
  api :error_response, :only => [:status]

  def behavior
    name == 'Mr. Bananas' ? 'Good' : 'Bad'
  end

  def favorite_number
    rand(10)
  end

  def status
    valid? ? 'OK' : 'Error'
  end
end

class Banana < ActiveRecord::Base
  belongs_to :monkey

  include ApiTwister

  define_api {|a| a.method :edible}

  api :request
  api :response

  def edible
    created_at > 10.days.ago ? 'Yes' : 'No'    
  end
end

# TODO - more docs

Development

Fork away. Please create a topic branch and write passing tests if you are submitting a pull request.

git clone git://github.com/yourname/api-twister.git
cd api-twister
bundle install
rake test
git checkout -b your_fix

Credits

Scott Jacobsen

Tee Parham

About

Ruby API specification DSL

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages