Rails 3. How to add an API to a rails app
I want to build a simple API that can be accessed by myself in other clients. I want to use Rails 3 to build it but I do not know how to do it. I know that Rails got this more or less build in but I do not know how to inter开发者_如何学Pythonact with it.
Is there any resources on the Internet that I can read up on how to turn my Rails 3 application into a server with a remote API?
Thankful for all input.
Despite of what had been already told, you can start with rails api screencast. Although it's meant for an API only application.
If you want to add and API to an existent full rails app, check this blog post which covers the essentials on a Rails API, including tips for speed-up.
Since this should be a requirement too, for securing your API there's also a screencast on the subject: #352 Securing an API
Yehuda Katz and Ryan Bigg's book, Rails 3 in Action, has a chapter on building a test-driven JSON API on top of the example application that runs through the entire book.
The code for the sample application in the book, Ticketee, is open source and can be found on GitHub. In particular, everything API-related is namespaced under /app/controllers/api and you can find plenty of RSpec tests in /spec/api.
a good starting point might be reading up on REST and responders
Then to interact with the API from another rails app, you can use ActiveResource. There's a Railscast on it.
An example:
#API side
class ProductsController < ApplicationController
respond_to :json
def index
@products = Product.all
respond_with(@products)
end
end
#Client
# models/product.rb
class Product < ActiveResource::Base
self.site = "http://your-api-app.com"
end
The rails-api gem is a Rails subset that only includes the minimum modules needed to create an API app. It's intended to be lightweight and faster than a normal Rails application.
Check http://railscasts.com/episodes/348-the-rails-api-gem for a nice tutorial on how to use the gem.
Came up with a blog post recently - describes in examples how to add API to an existing Ruby on Rails application. Covers topics like Rails Metal controllers, routing, views and security. Hope that will help.
精彩评论