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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s