Create a simple API with Ruby on Rails
Here are the few easy steps to creating a simple API in a Ruby on Rails project.
- Start a new rails app with the restful_authentication plugin by technoweenie: http://github.com/technoweenie/restful-authentication/
- The restful_authentication plugin allows for user accounts, but doesn't have any API authentication built in. If you want to make publicly available API keys for your users, you'll need to put this in so you can track API usage and deter any unauthorized use. So assuming you have restful_authentication all setup with defaults, follow this tutorial for setting up API authentication: http://www.compulsivoco.com/2009/05/rails-api-authentication-using-restful-authentication/
- Once you have the above api authentication applied, make sure all the actions that you want protected by the API authentication by adding a before filter:
before_filter :login_required, :only => [...array of actions to be protected...]
- To render out xml for a certain object, you can simply use a respond_to when you're ready to render xml in the controller.
- The above assumes you have an object that you want to return, and will dump the columns as needed. If you want a prettier or custom return xml, I would recommend using the built in Builder that allows you to specify exactly what xml you want by creating a new view file called action_name.xml.builder and changing the respond_to line to the following:
- In your action_name.xml.builder, use the xml builder syntax to create your own xml file. Here's a quick example:
- You should test all of this using curl
http://localhost:3000/controller/action/param.xml?api_key=SOME_API_KEY



