Create REST API Using Slim PHP Framework

I prefer slim framework for creating REST APIs because of two main reasons :

  1. It’s very lightweight and focused on REST and nothing else.
  2. It supports all the HTTP methods (GET, POST, PUT, DELETE).

I will create an API which will accept the JSON Data and store it into a file. Using GET Request you get these data in json format.

First you download the slim framework from here http://www.slimframework.com/install . Unzip the file and put it inside your server. Replace the contents of index.php .

<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim(array(
"MODE" => "development"
));
$app->post('/test', 'test');
$app->get('/test', 'get_data');
function test() {
 $request = file_get_contents('php://input');    //get the body of the http request
// $data_arr =json_decode($request,true);  //convert the json into array, you can manipulate the data the you you want
//store the json in a file
 $handle = fopen('data/test_data.json', 'w+');  // you must create a data folder in the same folder of index.php
 fwrite($handle, $request); 
echo "Success";
}
function get_data(){
$data=file_get_contents("data/test_data.json");  //read the json data from the file
echo $data; // return the data
}
?>

Now your api is  ready. You can test it using any rest client.
You can explore slim framework Documentation to create more complicated api.

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

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