Reputation: 203
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.
Upvotes: 1
Views: 140
Reputation: 4575
I have done several Api's in RoR, and these are the steps I usually take:
I usually create a controller for the api, lets call it ApiController, all the requests i do on my app go through that 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
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
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
Upvotes: 1
Reputation: 4436
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.
Upvotes: 0
Reputation: 3400
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
Upvotes: 2