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 . Unzip the file and put it inside your server. Replace the contents of index.php .

require 'Slim/Slim.php';
$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

Encoding and Decoding JSON Data in PHP

Encoding JSON Data ( convert an array into JSON Data)

Lets say you have 5 variables :






First you store these values in a associative array


$myArray = array(‘a’ => 1, ‘b’ => 2, ‘c’ => 3, ‘d’ => 4, ‘e’ => 5);

$json_data = json_encode ($myArray);

echo $json_data;


Output :   { “a” : 1, ” b” : 2, “c” : 3, “d” : 4, “e” : 5 }

Decoding JSON Data ( Converting JSON Data into Array)

Lets say you a variable containing JSON data

$myVar=’ { “a” : 1, ” b” : 2, “c” : 3, “d” : 4, “e” : 5 } ‘;


$myArray= json_decode ($myVar , true);


Output : array(5) { [“a”]=> int(1) [“b”]=> int(2) [“c”]=> int(3) [“d”]=> int(4) [“e”]=> int(5) }

Note : its an array of size 5.

To access value stored in c

<?  echo $myArray[‘c’]; ?>

output : 3