Here is a quick walkthrough.
Preparing the base application
Let me create a new rails application
$ rails new simple-message $ cd simple-message/
Now we will create a RESTful resource called Message, which will manage the messages coming from your mobile phones.
$ rails generate scaffold Message title:string content:text
Create a table that will contain the messages:
$ rake db:migrate
Start the limited server and point the browser to http://0.0.0.0{000/messages
From there, you can manually create new messages that will be displayed in a list.
Your API already exists
For each page that you can move in your browser, there is a corresponding view that accepts program calls from other clients.
If you look at http://0.0.0.0{000 /messages.xml, you will get an xml containing all your posts. With curl:
$ curl http://localhost:3000/messages.xml <?xml version="1.0" encoding="UTF-8"?> <messages type="array"> <message> <created-at type="datetime">2010-11-27T18:24:36Z</created-at> <title>Just a message</title> <updated-at type="datetime">2010-11-27T18:24:36Z</updated-at> <id type="integer">1</id> <content>With some content</content> </message> </messages>
Time to add a new message:
$ curl -X POST -H 'Content-type: text/xml' -d '<message><title>Hello</title><content>How are you</content></message>' http://0.0.0.0:3000/messages.xml <?xml version="1.0" encoding="UTF-8"?> <message> <created-at type="datetime">2010-11-27T18:40:44Z</created-at> <title>Hello</title> <updated-at type="datetime">2010-11-27T18:40:44Z</updated-at> <id type="integer">2</id> <content>How are you</content> </message>
Your Android client will need to act like a curl to add new messages.
Protect your web application
Now you need authentication to allow only a specific user to act as an administrator and restrict the use of your API. Before digging for a different way to implement authentication in Rails:
- Does your user need to authenticate before sending a message?
- if the web application accepts authentication from other services (i.e. Twitter, Facebook, Google, OAuth, OpenID ...) or against its own user database?
- Is your API open to other clients, or only your Android client can send messages?
- Do you need to know who sent the message (i.e. user login)?
- Do you want to block a single user or posting application in your web application?
You can find a good description of the various strategies here .