How to create a Restful Service using Slim Framework

REST stands for Representational State Transfer. Restful services are nothing but web services which are based on URIs to use resources. You can call data and functions which are added in the form of restful services from the restful glossary. In this tutorial we will see how to create a Restful Service using Slim Framework. Slim is very popular framework and light weight framework  especially used to create  Restful services. The following example demonstrates how to create functions and call those functions using route URLs.

RESTful service gives output mostly in the form of  JSON or  XML.

In this example, I am just using a table to get data as well as post data. There you have different type of

Follow the steps carefully to create restful service in Slim Framework.

  1.  Create a database in MYSQL and a table in it. Database and table names could be your choice.
  2. My table name here is scores which contains 3 fields named ScoreId, Name and Score. You can improve table as per your requirement.
  3. Now follow the code which contains 3 different methods to retrieve scores,  users (means players) and user for a particular player information.
  4. You need to change database username, passwords and table name accordingly in the given example.
  5. <?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    /**
     * Step 1: Require the Slim Framework using Composer's autoloader
     *
     * If you are not using Composer, you need to load Slim Framework with your own
     * PSR-4 autoloader.
     */
    require 'vendor/autoload.php';
     
    /**
     * Step 2: Instantiate a Slim application
     *
     * This example instantiates a Slim application using
     * its default settings. However, you will usually configure
     * your Slim application now by passing an associative array
     * of setting names and values into the application constructor.
     */
    $app = new Slim\App();
     
    /**
     * Step 3: Define the Slim application routes
     *
     * Here we define several Slim application routes that respond
     * to appropriate HTTP request methods. In this example, the second
     * argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete`
     * is an anonymous function.
     */
    $app->post('/scores', function ($request, $response, $args) {
        return addScore();
    });
     
    $app->get('/users', function ($request, $response, $args) {
       return getScore();
    });
     
    $app->get('/user[/{id}]', function ($request, $response, $args) {
         $id=$args['id'];
       return getScore2($id);
    });
     
     
     
    function getScore() {
         
    $servername = "localhost";
    $username = "narendra_lucky";
    $password = "123.123";
     $con = mysqli_connect($servername,$username,$password,"narendra_db2");
        $sql = "select * from scores";
      $result = mysqli_query($con,$sql);
        while($row=mysqli_fetch_assoc($result))
     
        {
            $users[] = $row;
        }
        echo json_encode($users);
      }
     
     
     
    function getScore2($id) {
         
    $servername = "localhost";
    $username = "narendra_lucky";
    $password = "123.123";
     $con = mysqli_connect($servername,$username,$password,"narendra_db2");
        $sql = "select * from scores where scoreId=$id";
      $result = mysqli_query($con,$sql);
        while($row=mysqli_fetch_assoc($result))
     
        {
            $users[] = $row;
        }
        echo json_encode($users);
      }
     
     
    function addScore(){
    $servername = "localhost";
    $username = "narendra_lucky";
    $password = "123.123";
    $con = mysqli_connect($servername,$username,$password,"narendra_db2");
        $scoreId = $_POST['scoreId'];
        $name = $_POST['name'];
        $score = $_POST['score'];
        $sql = "insert into scores(scoreId,name,score) values($scoreId,'$name',$score)";
        echo $sql;
        $result = mysqli_query($con,$sql);
        if($result)
        {
            $status = array("status"=>"1","message"=>"Added Successfully!");
            echo json_encode($status);
        }
        else 
        {
             $status = array("status"=>"0","message"=>"Not Added!");
            echo json_encode($status);
        }
        
    }
     
      
     
     
     
     
     
    /**
     * Step 4: Run the Slim application
     *
     * This method should be called last. This executes the Slim application
     * and returns the HTTP response to the HTTP client.
     */
     
    $app->run();