Creating a RESTful API using Slim php framework

Creating a RESTful API using Slim php framework

Rest API icon

Restful architectures are often used to create client/server network environments. REST, which stands for representational state transfer, is a simpler alternative to SOAP and WSDL services, but still maintains great features like platform-independence and language independence. REST services explicitly use HTTP methods when implementing their calls, therefore any good API should support the basic GET, POST, PUT, and DELETE methods. Along with knowing the HTTP methods you must understand the HTTP status codes as well. If you are unfamiliar with what the various codes mean you can read about them here .

For this article we will be using the slim PHP micro framework to implement the RESTful API. Slim was chosen because it is very light weight, clean, supports all the HTTP methods, and also provides support for middleware layers. Along with slim you will need a web server (apache or nginx), PHP, and MySQL installed before proceeding. Once you’ve gotten all the necessary files you can begin.

You must begin the PHP script by including the slim libraries

 require 'Slim/Slim.php';

Next you will create a new instance of your app and define the routes that you will be using

$app = new Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->get('/user/:id', 'getUser');
$app->post('/user', 'addUser');
$app->put('/user/:id', 'updateUser');
$app->delete('/user/:id', 'deleteUser');
$app->run();
The routes contain the desired URL for the call followed by the function that is to be called upon reaching that path.

Once you have set up all the routes that you need you can then start writing the functions that handle the data manipulation.

GET example:

function getUsers() {
$sql = "select * FROM users";
  try {
    $db = getConnection();
    $stmt = $db->query($sql);
    $users = $stmt->fetchAll(PDO::FETCH_OBJ);
    $db = null;
    echo json_encode($users);
  }
  catch(PDOException $e) {
    echo json_encode($e->getMessage());
  }
}

This function returns the data of all users in the JSON format.

POST example:

function addUser() { 
  global $app;
  $req = $app->request();
  $body = json_decode($req->getBody());

  $sql = "INSERT INTO users (`name`,`email`,`age`) VALUES (:name, :email, :age)";
  try {
    $db = getConnection();
    $stmt = $db->prepare($sql);
      $stmt->bindParam("name", $body->userName);
      $stmt->bindParam("email", $userEmail);
      $stmt->bindParam("age", $userAge);
      $stmt->execute();
      $db = null;
      echo json_encode($user);
  } catch(PDOException $e) {
      echo json_encode($e->getMessage());
  }
}

This function creates a new entry for the new users in our database. The values being passed into the SQL query are being bound in lines 9 and 10 and that information comes from the request body (line 4).

PUT example:

function updateUser($id) {
   global $app;
   $req = $app->request();
   $body = json_decode($request->getBody());

   $sql = "UPDATE users SET email=:email, age=:age WHERE id=:id";
   try {
     $db = getConnection();
     $stmt = $db->prepare($sql);
     $stmt->bindParam("email", $body->email);
     $stmt->bindParam("age", $body->age);
     $stmt->bindParam("id", $id);
     $stmt->execute();
     $db = null;
     echo json_encode($body);
   } catch(PDOException $e) {
     echo json_encode($e->getMessage());
   }
}

This function will update a row in the database with the supplied data from the request body.

Delete Example:

 
function deleteUser($id) {
   $sql = "DELETE FROM users WHERE id=:id";
   try {
     $db = getConnection();
     $stmt = $db->prepare($sql);
     $stmt->bindParam("id", $id);
     $stmt->execute();
     $db = null;
  } catch(PDOException $e) {
     echo json_encode($e->getMessage());
  }
}

The requested user will be removed from your database table.

The final part of code that is needed is the database connection code.

function getConnection() {
  $dbhost="127.0.0.1";
  $dbuser="root";
  $dbpass="";
  $dbname="testDB";
  $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  return $dbh;
}

Once you’ve gotten you all the code written you can now test your API to make sure that you code is returning the correct information and doing the desired actions. You can test them by opening your preferred shell and running the following cURL commands

Get Users:

curl –i –X GET http://localhost/rest/api/users

Post (create new) User:

curl –i –X POST –d '{"name":"John Doe","email":"anemail@gmail.com","age":28}' http://localhost/rest/api/user

Put (update) User:

curl –i –X PUT –d '{"email":"jdoe@yahoo.com","age":38}' http://localhost/rest/api/user/8

Delete User:

curl –i –X DELETE http://localhost/rest/api/user/8

Now that you've gotten your RESTful API working you can implement these calls into your future projects.

Further slim documentation can be found here.

© 2017 SpinSpire All rights reserved.