Develop REST API Using Sinatra (A Ruby Framework)

This REST API accepts JSON  Data and stores it in a file. You can retrieve these data using GET Request.

require 'rubygems'
require 'sinatra'
require 'sinatra/json'
require 'json'
require 'sinatra/cross_origin'
configure do
 enable :cross_origin
end
set :environment, :production

post '/test' do
 cross_origin :allow_origin => '*',
 :allow_methods => [:post],
 :allow_credentials => true,
 :max_age => "60"
 data = JSON.parse(request.body.read)
 aFile = File.new("data/data.json", "w+")
if aFile
 aFile.syswrite(data)
end
 json data
end

get '/test' do
 cross_origin :allow_origin => '*',
 :allow_methods => [:get],
 :allow_credentials => true,
 :max_age => "60"
 aFile = File.new("data/data.json", "r+")
if aFile
 content = aFile.sysread(100)
end
 json content
end

You can test this api using REST Clients (Browser extensions).

You can also test it using curl -
 curl -i -X POST -d '{"blog" : "codegem"}' localhost:4567/test
Advertisements

Getting Started With Sinatra (Ruby Framework) on Windows

Sinatra is a free and open source software web application library and domain-specific language written in Ruby. It is an alternative to other Ruby web application frameworks such as Ruby on Rails, Merb, Nitro and Camping.
Getting Started With Sinatra (For Development)
1. Install latest version of Ruby : You can download the windows installer from http://rubyinstaller.org/.
2. Set path : C:\(ruby install directory)\bin;
3. Go to command promt. Type this command to install Sinatra : gem install Sinatra (if path is not set then go to C:\Ruby193\bin and then run the command from cmd).
4. Install Sinatra_contrib : gem install sinatra-contrib (after installing this you need not to restart the server with every change in your file)

Now you are ready to build your first app with Sinatra.
Step 1: create your project directory “myproject” anywhere in your computer.
Step 2: create a new file test.rb and add these lines

 require 'rubygems'
 require 'sinatra'
get '/firstapp' do
 "Welcome to my first Sinatra App !"
 End

Step 3 : In command Prompt, traverse to you project directory and run this command
ruby test.rb
If your path is not set then you will have to run it from C:\Ruby193\bin directory.
Step 4 : Now go to http://localhost:4567/firstapp

You will see the webpage with message “Welcome to my first Sinatra App !”

So you have Created your First App In Sinatra