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

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