質問

Trying to implement API calls. What goes in the controller? I think I should create API an API view. Should I use a one of the API gems?

I'm trying to use my first app to write to the database. My 2nd App will use a web API to GET/POST from first app's uri for fields that would share same data.

役に立ちましたか?

解決

Take a look at rabl gem it will assist you to generate JSON views using your current controllers, From this you can get the idea of how JSON APIs work and proceed to namespacing your controllers and routes for your API. For http requests between your two apps, you can use either httparty or typhoeus gems

他のヒント

I have done several Api's in RoR, and these are the steps I usually take:

  1. Create a restfull Api:

I usually create a controller for the api, lets call it ApiController, all the requests i do on my app go through that controller

  1. Authenticate the api controller:

for the sake of simplicity here is a non secure way to authenticate the users who use your api:

class ApiController < ApplicationController
  before_filter :apiauth

  private 

  def apiauth
    if request.headers["ApiAuth"]!='IguD7ITC203'
      raise "error"
    end
  end
end
  1. create some mothods and responses for your api:

here is a simple method you can implement on the controller:

def successOrder
  @order=Order.find_by_id(params['id'])
  if @order
    @order.status=params['status']
    if @order.save
      render :json => {:status => "true", :order => {:id => @order.id, :status => @order.status}}
    else
      render :json => {:status =>"false", :errors => @order.errors.full_messages }            
    end 
  else
      render :json => {:status => "false", :errors => ["Invalid Order Id"]}
  end
end
  1. update your routes:

sometimes I like to wildcard my routes for my api, like this:

match '/:action', :to => 'api#%{action}', :constraints =>  lambda {|r| r.subdomain.present?  && r.subdomain == 'api'} , :via => [:post]

Finnaly take a look at gems like Jbuilder that can build you awsome responses for your jsons. hope it helps

I recently created an API which served mobile and web application. I used RABL gem templating system and i was able to customize my API views as i wanted. You can use RABL to generate JSON and XML based APIs from any ruby object.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top