The previous day How to create REST API for Android app using PHP, Slim and MySQL – Day ½, we have learned fundamental concepts about REST API and preparing your development environment ready by installing the required tools needed. I hope everyone got good knowledge about REST and other technical areas. Also I am assuming that you got all the required tools installed.

Today we are going to learn how to setup a PHP project and writing the actual code for REST API. Also we’ll learn writing necessary SQL queries to perform database CRUD operations.

android rest api design using php mysql slim

8. Starting PHP Project

As we all know IDEs make development process easier. So I recommend you use an IDE for developing the PHP project instead of using plain notepad. You can go for Eclipse, Aptana Studio, PhpStorm or Netbeans. But I personally felt very comfortable using Netbeans for PHP projects.

PHP Project directory structure
The following diagram will give you an idea about the directory structure of the project which we are going to develop now.

task manager rest api php project directory structure

libs – All the third party libraries goes here. In our case we place Slim library here
include – All the helpers classes we build placed here
index.php – Takes care of all the API requests
.htaccess – Rules for url structure and other apache rules

Now let’s start the PHP project

1. Go to the directory where WAMP is installed. In general wamp will be installed in C:\wamp. (If you have installed any other software rather than WAMP, you should go to the directory recommended by that software).

2. As a first step we start with creating required directories. Inside wamp folder go to www folder (c:\wamp\www\) and create a folder named task_manager. This folder will be the parent directory of our project. Inside task_manager create two more folders named libs, include and v1.

3. Now the paste the Slim library inside libs folder. The download link for Slim is provided in previous part.

4. Normally Slim framework works when index.php includes in the url which makes url not well-formed. So using the .htacess rules we can get rid of index.php from the url and make some friendly urls. Inside v1 folder create a file named .htaccess and paste the following code. (Note that this file name shouldn’t include any additional extension in the name like .txt)

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]

8.1 Preparing Helper Classes

First we start writing set of helper classes required in this project. These helper classes provides necessary functions required to interact with the database.

5. Inside include folder create file named Config.php with following content. This file contains the entire project configuration like database connection parameters and other variables.

<?php
/**
 * Database configuration
 */
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'task_manager');

define('USER_CREATED_SUCCESSFULLY', 0);
define('USER_CREATE_FAILED', 1);
define('USER_ALREADY_EXISTED', 2);
?>

6. Create another class named DbConnect.php This class file mainly takes care of database connection.

<?php

/**
 * Handling database connection
 *
 * @author Ravi Tamada
 */
class DbConnect {

    private $conn;

    function __construct() {        
    }

    /**
     * Establishing database connection
     * @return database connection handler
     */
    function connect() {
        include_once dirname(__FILE__) . './Config.php';

        // Connecting to mysql database
        $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

        // Check for database connection error
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        // returing connection resource
        return $this->conn;
    }

}

?>

Encrypting the password
7. The best way to secure the user passwords is not store them as plain text, instead all the passwords should be encrypted before storing in db. The following class takes care of encrypting the user password. Create another file named PassHash.php and paste the following code.

<?php

class PassHash {

    // blowfish
    private static $algo = '$2a';
    // cost parameter
    private static $cost = '$10';

    // mainly for internal use
    public static function unique_salt() {
        return substr(sha1(mt_rand()), 0, 22);
    }

    // this will be used to generate a hash
    public static function hash($password) {

        return crypt($password, self::$algo .
                self::$cost .
                '$' . self::unique_salt());
    }

    // this will be used to compare a password against a hash
    public static function check_password($hash, $password) {
        $full_salt = substr($hash, 0, 29);
        $new_hash = crypt($password, $full_salt);
        return ($hash == $new_hash);
    }

}

?>

8. Now create another class named DbHandler.php This class is one of the important files in our project which provides necessary functions to perform CRUD operations on the database. Every function is self explanatory by it’s name and comments, I don’t have to have to explain much about them.

<?php

/**
 * Class to handle all db operations
 * This class will have CRUD methods for database tables
 *
 * @author Ravi Tamada
 */
class DbHandler {

    private $conn;

    function __construct() {
        require_once dirname(__FILE__) . './DbConnect.php';
        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }

    /* ------------- `users` table method ------------------ */

    /**
     * Creating new user
     * @param String $name User full name
     * @param String $email User login email id
     * @param String $password User login password
     */
    public function createUser($name, $email, $password) {
        require_once 'PassHash.php';
        $response = array();

        // First check if user already existed in db
        if (!$this->isUserExists($email)) {
            // Generating password hash
            $password_hash = PassHash::hash($password);

            // Generating API key
            $api_key = $this->generateApiKey();

            // insert query
            $stmt = $this->conn->prepare("INSERT INTO users(name, email, password_hash, api_key, status) values(?, ?, ?, ?, 1)");
            $stmt->bind_param("ssss", $name, $email, $password_hash, $api_key);

            $result = $stmt->execute();

            $stmt->close();

            // Check for successful insertion
            if ($result) {
                // User successfully inserted
                return USER_CREATED_SUCCESSFULLY;
            } else {
                // Failed to create user
                return USER_CREATE_FAILED;
            }
        } else {
            // User with same email already existed in the db
            return USER_ALREADY_EXISTED;
        }

        return $response;
    }

    /**
     * Checking user login
     * @param String $email User login email id
     * @param String $password User login password
     * @return boolean User login status success/fail
     */
    public function checkLogin($email, $password) {
        // fetching user by email
        $stmt = $this->conn->prepare("SELECT password_hash FROM users WHERE email = ?");

        $stmt->bind_param("s", $email);

        $stmt->execute();

        $stmt->bind_result($password_hash);

        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // Found user with the email
            // Now verify the password

            $stmt->fetch();

            $stmt->close();

            if (PassHash::check_password($password_hash, $password)) {
                // User password is correct
                return TRUE;
            } else {
                // user password is incorrect
                return FALSE;
            }
        } else {
            $stmt->close();

            // user not existed with the email
            return FALSE;
        }
    }

    /**
     * Checking for duplicate user by email address
     * @param String $email email to check in db
     * @return boolean
     */
    private function isUserExists($email) {
        $stmt = $this->conn->prepare("SELECT id from users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();
        return $num_rows > 0;
    }

    /**
     * Fetching user by email
     * @param String $email User email id
     */
    public function getUserByEmail($email) {
        $stmt = $this->conn->prepare("SELECT name, email, api_key, status, created_at FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        if ($stmt->execute()) {
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            return $user;
        } else {
            return NULL;
        }
    }

    /**
     * Fetching user api key
     * @param String $user_id user id primary key in user table
     */
    public function getApiKeyById($user_id) {
        $stmt = $this->conn->prepare("SELECT api_key FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        if ($stmt->execute()) {
            $api_key = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            return $api_key;
        } else {
            return NULL;
        }
    }

    /**
     * Fetching user id by api key
     * @param String $api_key user api key
     */
    public function getUserId($api_key) {
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE api_key = ?");
        $stmt->bind_param("s", $api_key);
        if ($stmt->execute()) {
            $user_id = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            return $user_id;
        } else {
            return NULL;
        }
    }

    /**
     * Validating user api key
     * If the api key is there in db, it is a valid key
     * @param String $api_key user api key
     * @return boolean
     */
    public function isValidApiKey($api_key) {
        $stmt = $this->conn->prepare("SELECT id from users WHERE api_key = ?");
        $stmt->bind_param("s", $api_key);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();
        return $num_rows > 0;
    }

    /**
     * Generating random Unique MD5 String for user Api key
     */
    private function generateApiKey() {
        return md5(uniqid(rand(), true));
    }

    /* ------------- `tasks` table method ------------------ */

    /**
     * Creating new task
     * @param String $user_id user id to whom task belongs to
     * @param String $task task text
     */
    public function createTask($user_id, $task) {        
        $stmt = $this->conn->prepare("INSERT INTO tasks(task) VALUES(?)");
        $stmt->bind_param("s", $task);
        $result = $stmt->execute();
        $stmt->close();

        if ($result) {
            // task row created
            // now assign the task to user
            $new_task_id = $this->conn->insert_id;
            $res = $this->createUserTask($user_id, $new_task_id);
            if ($res) {
                // task created successfully
                return $new_task_id;
            } else {
                // task failed to create
                return NULL;
            }
        } else {
            // task failed to create
            return NULL;
        }
    }

    /**
     * Fetching single task
     * @param String $task_id id of the task
     */
    public function getTask($task_id, $user_id) {
        $stmt = $this->conn->prepare("SELECT t.id, t.task, t.status, t.created_at from tasks t, user_tasks ut WHERE t.id = ? AND ut.task_id = t.id AND ut.user_id = ?");
        $stmt->bind_param("ii", $task_id, $user_id);
        if ($stmt->execute()) {
            $task = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            return $task;
        } else {
            return NULL;
        }
    }

    /**
     * Fetching all user tasks
     * @param String $user_id id of the user
     */
    public function getAllUserTasks($user_id) {
        $stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $tasks = $stmt->get_result();
        $stmt->close();
        return $tasks;
    }

    /**
     * Updating task
     * @param String $task_id id of the task
     * @param String $task task text
     * @param String $status task status
     */
    public function updateTask($user_id, $task_id, $task, $status) {
        $stmt = $this->conn->prepare("UPDATE tasks t, user_tasks ut set t.task = ?, t.status = ? WHERE t.id = ? AND t.id = ut.task_id AND ut.user_id = ?");
        $stmt->bind_param("siii", $task, $status, $task_id, $user_id);
        $stmt->execute();
        $num_affected_rows = $stmt->affected_rows;
        $stmt->close();
        return $num_affected_rows > 0;
    }

    /**
     * Deleting a task
     * @param String $task_id id of the task to delete
     */
    public function deleteTask($user_id, $task_id) {
        $stmt = $this->conn->prepare("DELETE t FROM tasks t, user_tasks ut WHERE t.id = ? AND ut.task_id = t.id AND ut.user_id = ?");
        $stmt->bind_param("ii", $task_id, $user_id);
        $stmt->execute();
        $num_affected_rows = $stmt->affected_rows;
        $stmt->close();
        return $num_affected_rows > 0;
    }

    /* ------------- `user_tasks` table method ------------------ */

    /**
     * Function to assign a task to user
     * @param String $user_id id of the user
     * @param String $task_id id of the task
     */
    public function createUserTask($user_id, $task_id) {
        $stmt = $this->conn->prepare("INSERT INTO user_tasks(user_id, task_id) values(?, ?)");
        $stmt->bind_param("ii", $user_id, $task_id);
        $result = $stmt->execute();
        $stmt->close();
        return $result;
    }

}

?>

8.2 Handling the API calls

Now we have all the required classes for the REST API. Now we can start the code to handle all individual api calls.

8. Inside v1 folder create a file named index.php and add the following code. Here we are including required libraries and other helper functions.

verifyRequiredParams() – This function verifies the mandatory parameters in the request.
validateEmail() – Verifies whether email address is valid one or not.
echoRespnse() – This function will echo the JSON response with a status code.

<?php

require_once '../include/DbHandler.php';
require_once '../include/PassHash.php';
require '.././libs/Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

// User id from db - Global Variable
$user_id = NULL;

/**
 * Verifying required params posted or not
 */
function verifyRequiredParams($required_fields) {
    $error = false;
    $error_fields = "";
    $request_params = array();
    $request_params = $_REQUEST;
    // Handling PUT request params
    if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
        $app = \Slim\Slim::getInstance();
        parse_str($app->request()->getBody(), $request_params);
    }
    foreach ($required_fields as $field) {
        if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
            $error = true;
            $error_fields .= $field . ', ';
        }
    }

    if ($error) {
        // Required field(s) are missing or empty
        // echo error json and stop the app
        $response = array();
        $app = \Slim\Slim::getInstance();
        $response["error"] = true;
        $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
        echoRespnse(400, $response);
        $app->stop();
    }
}

/**
 * Validating email address
 */
function validateEmail($email) {
    $app = \Slim\Slim::getInstance();
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response["error"] = true;
        $response["message"] = 'Email address is not valid';
        echoRespnse(400, $response);
        $app->stop();
    }
}

/**
 * Echoing json response to client
 * @param String $status_code Http response code
 * @param Int $response Json response
 */
function echoRespnse($status_code, $response) {
    $app = \Slim\Slim::getInstance();
    // Http response code
    $app->status($status_code);

    // setting response content type to json
    $app->contentType('application/json');

    echo json_encode($response);
}

$app->run();
?>

The JSON response

On calling every API request a JSON response will be issued with a HTTP status code. On the client side you have to verify the response http status code. If the status is 200, the request is processed successfully. Also you can notice a “error” node in the response. If the error value is true, that means some error occurred while processing the user data.

Api Calls without Authentication (without API key in the request header)

These calls don’t have to include Api Key in the request header. The main purpose of these calls is to interact with database without any authentication. User registration and login comes under this category.

⇒ User Registration

In order to interact with the API, the user has to register in our system first. Once he registered an API key will be generated and stored in the database. This API key will be private to that user only.

9. Add the following code in index.php. This function handles user registration.

/**
 * User Registration
 * url - /register
 * method - POST
 * params - name, email, password
 */
$app->post('/register', function() use ($app) {
            // check for required params
            verifyRequiredParams(array('name', 'email', 'password'));

            $response = array();

            // reading post params
            $name = $app->request->post('name');
            $email = $app->request->post('email');
            $password = $app->request->post('password');

            // validating email address
            validateEmail($email);

            $db = new DbHandler();
            $res = $db->createUser($name, $email, $password);

            if ($res == USER_CREATED_SUCCESSFULLY) {
                $response["error"] = false;
                $response["message"] = "You are successfully registered";
                echoRespnse(201, $response);
            } else if ($res == USER_CREATE_FAILED) {
                $response["error"] = true;
                $response["message"] = "Oops! An error occurred while registereing";
                echoRespnse(200, $response);
            } else if ($res == USER_ALREADY_EXISTED) {
                $response["error"] = true;
                $response["message"] = "Sorry, this email already existed";
                echoRespnse(200, $response);
            }
        });

In the following table you can find the API request information about the URL, HTTP method and the parameters needed to be posted.

URL /register
Method POST
Params name, email, password

Upon the successful registration the following json response will be issued.

{
    "error": false,
    "message": "You are successfully registered"
}

If the request is missing mandatory parameters the following json will be issued.

{
    "error": true,
    "message": "Required field(s) email, password is missing or empty"
}

⇒ User Login

10. Add the following code to handle user login. After verifying user credentials, the API Key for that user will be issued in the json response. The api key should be included in the request header in all remaining api calls.

/**
 * User Login
 * url - /login
 * method - POST
 * params - email, password
 */
$app->post('/login', function() use ($app) {
            // check for required params
            verifyRequiredParams(array('email', 'password'));

            // reading post params
            $email = $app->request()->post('email');
            $password = $app->request()->post('password');
            $response = array();

            $db = new DbHandler();
            // check for correct email and password
            if ($db->checkLogin($email, $password)) {
                // get the user by email
                $user = $db->getUserByEmail($email);

                if ($user != NULL) {
                    $response["error"] = false;
                    $response['name'] = $user['name'];
                    $response['email'] = $user['email'];
                    $response['apiKey'] = $user['api_key'];
                    $response['createdAt'] = $user['created_at'];
                } else {
                    // unknown error occurred
                    $response['error'] = true;
                    $response['message'] = "An error occurred. Please try again";
                }
            } else {
                // user credentials are wrong
                $response['error'] = true;
                $response['message'] = 'Login failed. Incorrect credentials';
            }

            echoRespnse(200, $response);
        });
URL /login
Method POST
Params email, password

On successful login the following json will be issued.

{
    "error": false,
    "name": "Ravi Tamada",
    "email": "ravi@gmail.com",
    "apiKey": "940bb12af8d7b040876f60f965c5be6d",
    "createdAt": "2014-01-07 23:38:35"
}

If the credentials are wrong, you can expect the following json.

{
    "error": true,
    "message": "Login failed. Incorrect credentials"
}

⇒ Verifying API Key

While dealing with task data, we need to identify the user using the API key in the request header by reading Authorization field. Basically we’ll look into database for matched API key and get the appropriate user. If the API key not present in users table, then we’ll stop the execution and echo the error json.

11. Add the following method in index.php. The method authenticate() will be executed every time before doing any task related operations on database.

/**
 * Adding Middle Layer to authenticate every request
 * Checking if the request has valid api key in the 'Authorization' header
 */
function authenticate(\Slim\Route $route) {
    // Getting request headers
    $headers = apache_request_headers();
    $response = array();
    $app = \Slim\Slim::getInstance();

    // Verifying Authorization Header
    if (isset($headers['Authorization'])) {
        $db = new DbHandler();

        // get the api key
        $api_key = $headers['Authorization'];
        // validating api key
        if (!$db->isValidApiKey($api_key)) {
            // api key is not present in users table
            $response["error"] = true;
            $response["message"] = "Access Denied. Invalid Api key";
            echoRespnse(401, $response);
            $app->stop();
        } else {
            global $user_id;
            // get user primary key id
            $user = $db->getUserId($api_key);
            if ($user != NULL)
                $user_id = $user["id"];
        }
    } else {
        // api key is missing in header
        $response["error"] = true;
        $response["message"] = "Api key is misssing";
        echoRespnse(400, $response);
        $app->stop();
    }
}

If the api key is missing in the request header, the following json will be echoed with 400 status code.

{
    "error": true,
    "message": "Api key is misssing"
}

If the api key is not valid following json will echoed with 401 status code.

{
    "error": true,
    "message": "Access Denied. Invalid Api key"
}

Api Calls with Authentication (Including API key in the request)
Following are the API calls should have an Api Key in the request header. These api calls primarily deals the user’s task data like creating, reading, updating and deleting.

⇒ Creating New Task

12. Add the follwing method to create a new task. Here you can notice that authenticate method is called to verify the Api key before inserting a new task.

/**
 * Creating new task in db
 * method POST
 * params - name
 * url - /tasks/
 */
$app->post('/tasks', 'authenticate', function() use ($app) {
            // check for required params
            verifyRequiredParams(array('task'));

            $response = array();
            $task = $app->request->post('task');

            global $user_id;
            $db = new DbHandler();

            // creating new task
            $task_id = $db->createTask($user_id, $task);

            if ($task_id != NULL) {
                $response["error"] = false;
                $response["message"] = "Task created successfully";
                $response["task_id"] = $task_id;
            } else {
                $response["error"] = true;
                $response["message"] = "Failed to create task. Please try again";
            }
            echoRespnse(201, $response);
        });
URL /tasks
Method POST
Params task

On successful creation of new task following json will be issued. If you got this json, you can see new row inserted in tasks and user_tasks tables.

{
    "error": false,
    "message": "Task created successfully",
    "task_id": 1
}

⇒ Getting All Tasks

13. Following method will list down all user’s tasks. We don’t have to submit any params for this api call.

/**
 * Listing all tasks of particual user
 * method GET
 * url /tasks          
 */
$app->get('/tasks', 'authenticate', function() {
            global $user_id;
            $response = array();
            $db = new DbHandler();

            // fetching all user tasks
            $result = $db->getAllUserTasks($user_id);

            $response["error"] = false;
            $response["tasks"] = array();

            // looping through result and preparing tasks array
            while ($task = $result->fetch_assoc()) {
                $tmp = array();
                $tmp["id"] = $task["id"];
                $tmp["task"] = $task["task"];
                $tmp["status"] = $task["status"];
                $tmp["createdAt"] = $task["created_at"];
                array_push($response["tasks"], $tmp);
            }

            echoRespnse(200, $response);
        });
URL /tasks
Method GET
Params

Following json will be issued for list of tasks. The “tasks” represents list of tasks as an array. Also if the “status” is 0, that means the task is not done yet.

{
    "error": false,
    "tasks": [
        {
            "id": 1,
            "task": "Complete REST article by Sunday",
            "status": 0,
            "createdAt": "2014-01-08 23:35:45"
        },
        {
            "id": 2,
            "task": "Book bus tickets!",
            "status": 0,
            "createdAt": "2014-01-08 23:56:52"
        }
    ]
}

⇒ Getting Single Task

14. Following method will fetch details of single task. You need to append the task id with a / to url. For an example if you want details of task 15, the url will be /tasks/15.

/**
 * Listing single task of particual user
 * method GET
 * url /tasks/:id
 * Will return 404 if the task doesn't belongs to user
 */
$app->get('/tasks/:id', 'authenticate', function($task_id) {
            global $user_id;
            $response = array();
            $db = new DbHandler();

            // fetch task
            $result = $db->getTask($task_id, $user_id);

            if ($result != NULL) {
                $response["error"] = false;
                $response["id"] = $result["id"];
                $response["task"] = $result["task"];
                $response["status"] = $result["status"];
                $response["createdAt"] = $result["created_at"];
                echoRespnse(200, $response);
            } else {
                $response["error"] = true;
                $response["message"] = "The requested resource doesn't exists";
                echoRespnse(404, $response);
            }
        });
URL /tasks/id (id should be replaced with task id)
Method GET
Params

The details of a single task will be in following json format.

{
    "error": false,
    "id": 2,
    "task": "Book bus tickets!",
    "status": 0,
    "createdAt": "2014-01-08 23:56:52"
}

If you pass a task id which is not there in the database, you will get 404 not found error.

⇒ Updating Task

15. Following code will take care of updating a task. The url for this api call is same as getting the details of single task, only difference is we should use PUT method instead of GET.

/**
 * Updating existing task
 * method PUT
 * params task, status
 * url - /tasks/:id
 */
$app->put('/tasks/:id', 'authenticate', function($task_id) use($app) {
            // check for required params
            verifyRequiredParams(array('task', 'status'));

            global $user_id;            
            $task = $app->request->put('task');
            $status = $app->request->put('status');

            $db = new DbHandler();
            $response = array();

            // updating task
            $result = $db->updateTask($user_id, $task_id, $task, $status);
            if ($result) {
                // task updated successfully
                $response["error"] = false;
                $response["message"] = "Task updated successfully";
            } else {
                // task failed to update
                $response["error"] = true;
                $response["message"] = "Task failed to update. Please try again!";
            }
            echoRespnse(200, $response);
        });
URL /tasks/id (id should be replaced with task id)
Method PUT
Params task, status (0 or 1)

Upon successful updation you will get following json.

{
    "error": false,
    "message": "Task updated successfully"
}

⇒ Deleting Task

16. Again delete task url is same as update task, but this requires DELETE method.

/**
 * Deleting task. Users can delete only their tasks
 * method DELETE
 * url /tasks
 */
$app->delete('/tasks/:id', 'authenticate', function($task_id) use($app) {
            global $user_id;

            $db = new DbHandler();
            $response = array();
            $result = $db->deleteTask($user_id, $task_id);
            if ($result) {
                // task deleted successfully
                $response["error"] = false;
                $response["message"] = "Task deleted succesfully";
            } else {
                // task failed to delete
                $response["error"] = true;
                $response["message"] = "Task failed to delete. Please try again!";
            }
            echoRespnse(200, $response);
        });
URL /tasks/id (id should be replaced with task id)
Method DELETE
Params

You will get following json if the task is deleted successfully.

{
    "error": false,
    "message": "Task deleted succesfully"
}

Here we completes the PHP and MySQL part. Now it’s time to move on to testing the API just to make sure that whatever code we have written is working.

Testing the API

Following is the list of URL we need to test using Chrome Advanced REST client extension with possible combinations of inputs.

URL Method Parameters Description
http://localhost/task_manager/v1/register POST name, email, password User registration
http://localhost/task_manager/v1/login POST email, password User login
http://localhost/task_manager/v1/tasks POST task To create new task
http://localhost/task_manager/v1/tasks GET Fetching all tasks
http://localhost/task_manager/v1/tasks/:id GET Fetching single task
http://localhost/task_manager/v1/tasks/:id PUT Updating single task
http://localhost/task_manager/v1/tasks/:id DELETE task, status Deleting single task

The following video shows you how to test the API thoroughly.

What’s Next?

Until now we have done a great job by developing fully functional REST services from scratch. But the services are limited to localhost. In other words your app can’t consume them if you want your app to be on playstore. So to make the services globally accessible, we need to host them on a public server. In the next part Android Hosting PHP, MySQL RESTful services to DigitalOcean, you will learn the complete process of buying the hosting space, deploying the services and finally mapping to a real domain URL.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Bla Bla Bla

    Ravi, does every user get a table named task created for them on the Database?

    • No, we have to create the table using the sql queries mentioned in the first part of this tutorial.

      • Bla Bla Bla

        I know we did create a table in the first part, but you know we have users. So, for every user, there’ll be a table Task for them autogenerated or it’s just that table task that’ll take care of it all. I’m actually building an application and finding it hard to use the REST cause, I’m having problem structuring the Database itself, cause I’m a novice when it comes to databases. Thank You.

        • Hi,

          There will be always one table tasks. For every user there won’t be a separate task table created.

          Every task is inserted as a row in task table. The relation between task row and user will be stored in user_tasks table where user_id and task_id will be stored.

          • Bla Bla Bla

            Ohw, now I dig. Very brilliant an idea. Thank You. And, we are waiting for the p3

  • xDroid

    I am working on Mac and using MAMP . I have created task_manager in my htdocs folder because there was no www folder there in Application/MAMP/ . I have created .htaccess file in root of task_manager and added all the code accordingly but I am not able to access my code on the server Its been started showing MAMP webpage but when I try to open that URL it just show 404!
    Please help me with MAC setup or what I am doing Wrong! 🙁

    • xDroid
      • You need to access the full url path with correct HTTP method. If you access just http://localhost:8888/MAMP/task_manager/ you will get 404

        You should access full url
        http://localhost:8888/MAMP/task_manager/v1/register with POST method only.

        • xDroid

          I have tried with post method with full URL and just 404 !
          Status
          404 Not Found
          This !

          • Could you post the screenshot of that error.

          • Bakus Seifer

            Make sure “$app->run();” is the last line of code in index.php, after all the “/register”, “/login”, ….

        • Andrew Nyago

          By that, do you mean should have:
          $app->post(‘http://192.168.43.40/androidchatter/task_manager/v1/register/’, function () use ($app) {

          as my call to regster please?

          My result:

          404 Not Found

          Not Found
          The requested URL /androidchatter/task_manager/v1/register was not found on this server.

          Apache/2.4.7 (Ubuntu) Server at 192.168.43.40 Port 80

    • John

      The .htaccess file should be in the “v1” directory, NOT in “task_manager”.
      This is clear from the image showing the project structure at the beginning of the article, but not in the text… The downloadable code archive has all files in correct locations…

      • Thanks John for the correction. Updated the article.

  • nasznjoka

    Hi Ravi thanks once again for this contribution to our droid life. I have this question if you can help me. What is the best way of turning a website which is not responsive into an android app? I ve been seeing parsing but i don’t exactly know how to work with it better and when you want to apply it to the website then its a disaster to me

    • Could you tell what do you mean by “turning website into android app”?

      • nasznjoka

        I mean to parse website content into an app for example like linkedin web looks just like their android app. So i want to know how to whether native or frameworks

        • That actually can be done using responsive page which adjusts to screen size. You have to design your page in responsive way.

          Normally nobody will do a parse and prepare a page on android app. You have to use webview for it.

          • siddhu

            WIthout responsive page nobody cant parse

          • Zaphod Beeblebroks

            what is exactly meaning of “responsive page” we are talking about here? How responsive is related with parsing html? There is some misunderstanding here..

          • nasznjoka

            Thanx man, but i just wish i could know more. I ve gone through the library in here but i have not seen such a tutorial

          • Zaphod Beeblebroks

            I think I understood a bit different his question.. Let’s say there is a news portal which get updated severl times per day but it doesn’t offer rss, json, gson or smth similar, but just html.. Let’s say there is a specific table of home page of this portal which list headlines. Is it possible to make web app (Google App Engine or similar platform) which will from time to time parse that home page, get the table and generate json file which will be exposed on specific request? That why we make android app, we get the json file and we display it in app interface and all “heavy processing of parsing” is done in the cloud. Additionally android app uses less internet data by fetching just newest json instead of whole html page source. What about that? What should be used for web app? Where to host it? 10q

          • nasznjoka

            Yes thats what i was asking for thank Zaphod for clarifying to make an app for a site but with different organization of menus, contents to the site itself

      • solomon

        waiting for 3rd part please make it 😀

    • shashi

      i m getting ,,,,,,”Required field(s) name, email, password is missing or empty” on register

  • Very nicely written code 🙂

  • siddhu

    Stunning!!!

  • Mat

    You are the best Ravi!! 🙂 Thank You

  • meirariel

    What does the Slim framework add other than JSON encoding? What code did we save writing by using it?

    • Hi Meirariel,

      JSON encoding is not the functionality of Slim framework. json_encode() is native function of PHP.

      Slim actually takes care of routing and the method of url $app->get(‘/route’) – . Also slim provides middle layer where we can execute “authenticate” method.

      If you go through this doc, you can find lot more options of slim.
      http://docs.slimframework.com/

      • meirariel

        Thanks. Your tutorials are so well thought out and clear. Much appreciated.

        • You are welcome and thanks for the appreciation 🙂

  • derpina

    Ravi, you are the best. Thank you for the article.

  • meirariel

    If I wanted to store the user’s picture on the cloud, together with their other account details, how would you recommend doing that?

  • tan hieu Huynh

    I try run Advanced REST client as demo but occur error 500 Internal Server Error, Pls help me fix it. Thank!

    • Guest

      are you using chrome?

  • babazumbula

    I’m also getting error 50. My Appache error log says:
    [Fri Jan 24 15:51:52 2014] [alert] [client 127.0.0.1] C:/wamp/www/task_manager/.htaccess: Invalid command ‘RewriteEngine’, perhaps misspelled or defined by a module not included in the server configuration

    but, still I dunno how to fix it

  • babazumbula

    Solved, I was missing line…
    So I added line
    LoadModule rewrite_module modules/mod_rewrite.so
    in my httpd.conf

  • Steve

    Love this. It will help me complete my project http://www.e-schedulebuilder.com. But my question is. Do I need oauth1.0a or 2.0 and an apikey for API protocols? I am designing software that will allow users to view there schedules, update employee information and stuff all from the mobile application.

  • Steve

    Nice tutorial!
    Any clue when the third part will be ready?

    • Hi Steve, I am facing some error in third part. I am currently solving it.

      • Steve

        Thanks for the quick reaction.
        By the end of this week?

        Thanks again for the great tutorials.

        • Yeah, sure.

          • Marat Duisenov

            thank you for your work, my friend. I’m looking forward third part

          • Sorry mrt sen,

            I seems like I can’t post the third part as I stopped by some hosting service issues.

          • Marat Duisenov

            It’s a thousand pities!

          • Rasit Aklar

            10,000!!!

          • zxzx

            any update on these issues?

  • Евгений Храмов

    When i try register new user i hav an error “Required field(s) …. is missing or empty”
    Then I was trying to check fields by print print_r($_REQUEST)
    In my case $_REQUEST is empty.

    • John

      Thank for the great write up Ravi – I’m also getting the same issue as above…. any ideas?

      • In the error message it will clearly shows you what are the parameters are missing while posting to that url.

        If it says “Required fields(s) name, email missing”, then you should add name=’your name’ and email=’youremail@gmai.com’ in the request parameters.

        Check the testing video to know how I added parameters while making the request.

        • Евгений Храмов

          I was checking parameters in chome/firefox plugins and Fiddrer2
          In my case all parameters was sended to server, byt on the server side is empty.

          • jujusous3

            same problem, any solution ?

    • Guest

      In Advance REST Client, the drop-down list of ‘Set “Content-Type” header to overwrite this value.’ leave it as “application/x-www-form-urlencoded”

  • shyam

    where is third part of your tutorial

    • andlab

      Im also really waiting for it :)))
      thanks anyway

  • San

    This is one of the great tutorial! Thank you very much Ravi!!!

  • Marcus

    Hi, i have downloaded the code and uploaded it to my webserver and using chrome to test as per the example but i receive a server 500 message stating that the Response does not contain any data.Any ideas why i would be receiving this message. Thanks

    • Might be some php errors. Check your server php / apache error log file.

    • Oscar Serna

      Hey Marcus!, I’m facing the same problem. How did you solve it? what kind of error did you find? was it a directory issue or definitly it was a code error?

      thank you!

  • Jao

    when will be the third?

    • Marat Duisenov

      He can’t post the third part as He stopped by some hosting service issues.

  • dev

    nice tutorial

    but i m getting ,,,,,,”Required field(s) name, email, password is missing or empty” on register

    • Евгений Храмов

      I posted the same issue 12 days ago and no luck.

      • Marat Duisenov

        this example works for me

        • Евгений Храмов

          Good for you!

          • Marat Duisenov

            I meant it works

          • Marat Duisenov

            Asking the right question is half the answer

    • meirariel

      Make sure you’re sending the required fields in the body of the request and not as headers.

      • ZiLang

        I got the same problem. (I posted the 3 parameters as shown in video in body). Any other possible reason ?

        • shanice

          In Advance REST Client, the drop-down list of “Set Content-Type header to overwrite this value.” leave it as “application/x-www-form-urlencoded”

  • akhil nair

    nice tutorial….waiting for last part………

  • dev

    can any one tell me ,how to solve ,,,,,,,,,,,,,,,,,

    Required field(s) name, email, password is missing or empty” on register

  • Hao Zhou

    This is very nice tutorial. But I have two questions:

    1. Why do you use Slim ? I found it’s difficult to debug when there is one more layer there in php code
    2. Is there a way to separate different functions into different php files instead of all functions in index.php? Because it’ll be very difficult to find the functions if there are too many functions in the API.

  • dr tarik

    thanks for all your effort your are realy one reference
    one Q : how to change content-type to application/xml

  • Guest

    How to get JSON from your php in eclipse?

  • Dhiren

    Kindly, Give me some knowledge for SLIP Framework.

  • Dhiren

    SLIM* Framework

  • akhil nair

    Nice Tut….. I’m looking forward third part

  • brokenOval

    Great article, thanks for the post. Keep getting a strange error on Ubuntu. I can make Slim work for something simple like “Hello world”, however when it tries to call the include files I get an internal server error 500 – checked the error log and got the following message whenever I try to run (for example the /register API): “PHP Fatal error: DbHandler::__construct(): Failed opening required ‘/var/www/include./DbConnect.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/include/DbHandler.php on line 14”

    Anyone have an idea how to fix? Can confirm that Pear is installed on php and database is set up properly.

    • Jason Shen

      check your case as linux is case sensitie cheers

      • brokenOval

        Thanks Jason – all lowercase. I’m using an ubuntu distribution of apache if that helps. Any other ideas?

  • stephen

    amazing tutorial bro..keep up the good work

  • ape364

    Hi Ravi, good tutorial, thanks. can u tell why you need field ‘status’ in users table? i didnt find any use of this

  • Andrew

    Just wanted to say thank you! With minimum work on my end, I could just DL the code, change my DB config, and it worked, that easy! Read the Day 1 and Day2 of the article twice to get to know web services abit better too, but the video at the end really helped. Great job! For anyone having issues, just check your ReWrite module is working and edit the DB file, that’s it, great job!

  • zxzx

    So no 3rd part now?

  • neetu

    Your tutorial is great and very helpful.Can you post the third article if you not..then please tell me how to call rest webservice from android.I am so confused..

  • zxzx

    Any news about the 3rd part?

  • zxzx

    looks like the 3rd part ain’t coming.. 😉 thanx Ravi for all that u do

  • Hanimex

    Good tutorial. I ran through it on IIS8 (because I’m a masochist). I got to grips with the IIS URL Rewrite module and had to add in PUT and DELETE as allowed verbs for my PHP handler mapping but other than that it all worked. Thanks.

    • zxzx

      Can u plz post what u added Thx

      • Hanimex

        Well, for what it’s worth… I ended up with the following web.config file in my Task_Manager directory.

        Notes:
        1/ I created a “Task_Manager” application within a local website – the web.config changes were to that application only.
        2/ Instead of having to modify the .htaccess file that Apache uses, I had to use the URL Rewrite module (which sometimes isn’t installed by default on IIS) to create the “Task_ManagerApi Rule” above.
        3/ PHP is installed on *my* system using FastCGI – it might not be FastCGI on your setup and the .exe will be in a different location but, wherever it is, there will be a handler mapping for *.php files. The problem here is that IIS doesn’t allow PUT and DELETE verbs as default. I had to override this.
        4/ I used the IIS Manager to make the web.config changes above – I did not write the web.config file by hand (although you can if you are careful).

  • Shivendra Dubey

    Hi there i need your help, m constantly getting an error for as “Fatal error: Call to undefined method mysqli_stmt::get_result()” even though the mysqli and mysqlnd are enabled and running with latest php version. why the error is continue..

    • Shivendra Dubey

      please reply…

    • Douglas Roos

      I had the same issue but with GoDaddy hosting, So i’ve changed the $stmt->get_result()->$fetch_assoc() to $stmt->bind_result($id);

      while ($stmt->fetch()){

      $user_id = array(“id”=>$id);

      }

      And that’s it

      • Jason Shen

        Hi Gouglas
        just wondering how did you change your get task function to make it to work with bind_result instead of get_result, i am like stuck on that at the moment any help would be awesome cheers
        jason

  • Hoàng Bảo Dương Hùng

    Hi,
    I want upload image via rest api for android using php slim :(. Please guide for me.

  • gnuManiac

    Hi,
    great job but i need your help.
    For me “getting all tasks” it’s broken (500 Internal error – Response does not contain any data).

    Getting single task with no problems.

    • gnuManiac

      get_result() failure.
      Solved installing php5-mysqlnd

  • Muhammad Awais

    Mannnn !!! u r Awesome !!!! Thanksss alot for restful api tutorial.. :))) carry on

  • Guest

    Hi,

    Thanks for the Tutorial. I am having an issue when i Register an new user. I modified the parameters but i get the following message when i execute the request, “Response does not contain any data.”

    Could you kindly help me out. Thanks

  • Craig Daly

    Is anyone getting an ‘500 Internal Server Error’ message while using the Advanced Rest Client? I’m using MAMP on a Mac running OS X 10.9.2 Mavericks. Great tutorial, btw!!

    • Eugene Kiver

      You shoul’ve check your wamp directory for apache logs, I found the error desciption and googled for solution, in wamp you can click on it in windows bottom tray (or how they all it) then go to Apache->Apache Modules->Rewrite module. It turns out that it is disabled by default.

  • Craig Daly

    @walox checked the httpd.conf file & everything looks fine. here’s my output:

    Status
    500 Internal Server Error Loading time: 35
    Request headers
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.4 Safari/537.36
    Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
    Authorization: bf45c093e542f057caee68c47787e7d6
    Content-Type: application/x-www-form-urlencoded
    Accept: */*
    DNT: 1
    Accept-Encoding: gzip,deflate,sdch
    Accept-Language: en-US,en;q=0.8
    Cookie: SQLiteManager_currentLangue=2

    Response headers
    Date: Sun, 30 Mar 2014 19:56:22 GMT
    Server: Apache/2.2.26 (Unix) mod_fastcgi/2.4.6 mod_wsgi/3.4 Python/2.7.6 PHP/5.5.10 mod_ssl/2.2.26 OpenSSL/0.9.8y DAV/2 mod_perl/2.0.8 Perl/v5.18.0
    X-Powered-By: PHP/5.5.10
    Content-Length: 1980
    Connection: close
    Content-Type: text/html

    and here’s the response callback:
    Slim Application Error
    #1 /Applications/MAMP/htdocs/manage_tasks/include/DbConnect.php(31): DbConnect::connect()
    #2 /Applications/MAMP/htdocs/manage_tasks/include/DbHandler.php(19): DbConnect->connect()
    #3 /Applications/MAMP/htdocs/manage_tasks/v1/index.php(74): DbHandler->__construct()
    #4 [internal function]: {closure}()
    #5 /Applications/MAMP/htdocs/manage_tasks/libs/Slim/Route.php(436): call_user_func_array(Object(Closure), Array)
    #6 /Applications/MAMP/htdocs/manage_tasks/libs/Slim/Slim.php(1307): SlimRoute->dispatch()
    #7 /Applications/MAMP/htdocs/manage_tasks/libs/Slim/Middleware/Flash.php(85): SlimSlim->call()
    #8 /Applications/MAMP/htdocs/manage_tasks/libs/Slim/Middleware/MethodOverride.php(92): SlimMiddlewareFlash->call()
    #9 /Applications/MAMP/htdocs/manage_tasks/libs/Slim/Middleware/PrettyExceptions.php(67): SlimMiddlewareMethodOverride->call()
    #10 /Applications/MAMP/htdocs/manage_tasks/libs/Slim/Slim.php(1254): SlimMiddlewarePrettyExceptions->call()
    #11 /Applications/MAMP/htdocs/manage_tasks/v1/index.php(339): SlimSlim->run()
    #12 {main}

    I can’t tell if it’s a php coding error based in the 1st 2 lines of the response callback or if it’s an MAMP issue.

  • Mert Aksoy

    PHP Fatal error: Call to undefined function apache_request_headers() in /public_html/task_manager/v1/index.php on line 20

    added this function:

    if(!function_exists(‘apache_request_headers’)) {
    function apache_request_headers() {

    $headers = array();

    foreach($_SERVER as $key => $value) {

    if(substr($key, 0, 5) == ‘HTTP_’) {

    $headers[str_replace(‘ ‘, ‘-‘, ucwords(str_replace(‘_’, ‘ ‘, strtolower(substr($key, 5)))))] = $value;

    }else if($key == “Authorization”){

    $headers[$key] = $value;

    }

    }

    return $headers;

    }

    }

    now i couldnt see the value authorization in headers

    • Jesús Expósito

      Any fix to this issue? I use a similar function but the result is the same. Can’t see the auth header.

      if(!function_exists(‘apache_request_headers’)){

      function apache_request_headers(){

      static $arh = array();

      if (!$arh){

      $rx_http = ‘/AHTTP_/’;

      foreach ($_SERVER as $key => $val){

      if(preg_match($rx_http, $key)){

      $arh_key = preg_replace($rx_http, ”, $key);

      $rx_matches = array();

      // do some nasty string manipulations to restore the original letter case

      // this should work in most cases

      $rx_matches = explode(‘_’, $arh_key);

      if( count($rx_matches) > 0 and strlen($arh_key) > 2 ){

      foreach($rx_matches as $ak_key => $ak_val)

      {

      $rx_matches[$ak_key] = ucfirst($ak_val);

      }

      $arh_key = implode(‘-‘, $rx_matches);

      }

      $arh[$arh_key] = $val;

      }

      }

      }

      return $arh;

      }

      }

      • dfdsafsdds

        what r u doing bro 🙂

    • Brendan

      Ravi,

      A million thanks for this – it is easily the best example on the net of an authorization based restful api for PHP.

      Also it is brilliantly presented and coded – big kudos to you!!!

      Hi – I’ve just got this working on PHP 5.3 install – where the apache_request_headers does not exist.

      You need to follow up with two changes.

      1. Update your .htaccess file with

      RewriteRule .* – [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]

      This will add the variable HTTP_AUTHORIZATION such that $_Server will report on it.

      2. In the replacement function – the process to produce first character uppercase needs changed

      From:
      $rx_matches[$ak_key] = ucfirst($ak_val);

      To:
      $rx_matches[$ak_key] = ucfirst(strtolower($ak_val));

      Basically the function ucfirst does not work if the variable is already uppercase.

      Do both of these changes and voila – Authorization is presented and the scripts work.

  • Hi there are 2 errors in the DbHandler.php and DbConnect php files. You need to remove the “.” in the “./DbHandler” and “./Config.php” expression at lines 15.

  • Dũng

    how to register direct on url
    example api other: domain/Servers/Login/password:12z/username:12z

    how to use in your project.
    please help me.

  • endder

    Any news about the 3rd part?

  • jpgrassi

    Great post, thanks!

    I have only one question, all your methods use the parameters in the body. What changes do I need to make to accept json as parameters instead of body parameters?

    • schlocke

      I believe all request have a body, so instead of:

      parse_str($app->request()->getBody(), $request_params);

      you would do:

      $array = array();
      $array = json_decode($app->request()->getBody());

  • Guest

    thanks for all your effort man, I have a problem in the file DbHandler.php exactly in the line 221:

    $new_task_id = $this->conn->insert_id;

    where is defined insert_id ?

    thanks.

  • meka troniko

    muchas gracias!

  • Kalpesh Lodha

    Very Nice Tutorial….
    Thanks for your efforts….

  • villdre

    Hi – thank for the amazing & detailed tutorial … I am using MAMP on Mac (rather than WAMP on Windows), and have tested that my server is working fine. I have also followed all the steps in this tutorial. But I continuously get a 404 error when trying the POST method (or any other method) as per above. I am using the Chrome Advanced Rest Client and trying to access the following URI: http://localhost:8888/task_manager/v1/register

    (My server is on port 8888).
    Any hints on why I might be getting 404 would be greatly appreciated.
    Thanks in advance (and apologies for posting this as a bug earlier).

    • Eugene Kiver

      Just put in this folder some other .php file and check whether this path is acessible. If yes. Then you might be having the problem of php beginners who don’t know that $app->run(); should go AFTER the methods like $app->get(… So just download the source rename it to .zip and see how v1/index.php should look like, or copy’n’paste all the methods after the app->run.

    • Eugene Kiver

      And one more thing, for WAMP’s default settings include empty password field. While MAMP’s pass is “root”, so you have to edit line 6 in include/Config.php to “define(‘DB_PASSWORD’, ‘root’);” and yes you should include port 8888 in your chorme REST call

    • Zak

      I had the same problem, and apparently when I pasted the code for the functions that require authentication, I did that after $app->run() in index.php. Make sure you paste those functions that require authentication BEFORE $app->run();

  • Michael

    thanks allot

  • Eugene Kiver

    Can you update the source code? When I try to download it, I get a 66k file named Android without extension

    • Eugene Kiver

      manually adding .zip extension solved the problem

  • Classic example for beginners. Thank you very much.

    We are Test using Chrome Advanced REST client extension. Can anyone explain or PUT code to test with-in php file. (May be it was so easy but for beginners it good to find here)

  • Diego

    Hi, do you have an example for calling the api with ajax?

  • Diego

    Sorry, here are test lines:

    var dataTest = { “name”: “test”, “email”: “pepe@peperoni.com”, “password”: “sarasa” }
    var urlAjax = “http://localhost:8080/RSApi/v1/register”;

    $.ajax({
    type: “POST”,
    url: urlAjax,
    contentType: “application/json”,
    data: dataTest ,
    success: function(data) { alert(“ajax worked”); },
    error: function(data) {console.log(data); },
    dataType: ‘json’
    });

    I tried sending it as json object but with no success.

  • Guest

    Hello,
    Thank you very much for this tutorial.

    Can you please tell me how to return the logged in user (in android application) information by this url $app->get(‘/me’.

    Thank you.

  • Guest

    “500 Internal Server Error”

    • hakim

      i have the same probleme ^^

    • Bibash Shah

      If you are copying code exactly check once. I had same problem and what I was mistaken was the Config.php instead i had made config.php.

  • Gourav shrivaspati

    Help me to create data base for this ….

  • Bala Vishnu

    Hello, great tutorial. It works fine in my localhost using the WAMP server but it dosen’t work in my APACHE server….

  • Brendan

    Ravi,

    A million thanks for this – it is easily the best example on the net of an authorization based restful api for PHP.

    Also it is brilliantly presented and coded – big kudos to you!!!

    To all of the people struggling with apache_request_headers_not working – I’ve just got this working on PHP 5.3 install – where the apache_request_headers does not exist.

    You need to follow up with two changes.

    1. Update your .htaccess file with

    RewriteRule .* – [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]

    This will add the variable HTTP_AUTHORIZATION such that $_Server will report on it.

    2. In the replacement function – the process to produce first character uppercase needs changed

    From:
    $rx_matches[$ak_key] = ucfirst($ak_val);

    To:
    $rx_matches[$ak_key] = ucfirst(strtolower($ak_val));

    Basically the function ucfirst does not work if the variable is already uppercase.

    Do both of these changes and voila – Authorization is presented and the scripts work.

    • gkm

      Good work for pointing that out but I would like to ask …. How is the api_key supposed to be sent as part of the headers …..How do i include it in the request that I’m making??? Thanks

    • Yakup Başer

      i get an error on tht function:
      Call to undefined method mysqli_stmt::get_result() in /home1/beysplay/public_html/task_manager/include/DbHandler.php on line 268

      public function getAllUserTasks($user_id) {

      $stmt = $this->conn->prepare(“SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?”);

      $stmt->bind_param(“i”, $user_id);

      $stmt->execute();

      $tasks = $stmt->get_result(); <<<close();

      return $tasks;

      }

  • ozzner

    have problems
    500 and 404

  • ozzner

    wamp server 2.2d

  • Bilal Inamdar

    500 problem
    Solution : turn on rewrite module in apache

    • Miguel Lozano

      ty

  • Bilal Inamdar

    You have create a very good tutorial… I do not say so easily… Please include a Login system scripts in PHP for android and normal web browser. Because this is the only piece remaining in your master piece

  • Tom Lawton

    Thanks for a great tutorial. I was having a bit of trouble with 404 errors in the beginning and I needed to modify the rewrite rule to, probably due to the host I was using. Hopefully this will help others having the same issue:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ /task_manager/v1/index.php [QSA,L]

    • andrick

      I think that’s because the author forgot to mention where he defined %{ENV:BASE}

      • Andrew Nyago

        Thanks for that tip.
        Where did he define it please?
        Let me search forit using ack.
        If i don’t find it, I will deem myself beaten.
        I’m extremely new to php and i’m just looking for aworking sample for my Android App.

      • Andrew Nyago

        CANT FIND ANY REFERENCE TO ENV:BASE. CAN ANYONE HELP?

    • Harish Sn

      can u tell me how to write rewrite rule for subdomains?

    • Andrew Nyago

      what can I do if my drectory structure is like so:
      http://localhost/androidchatter/task_manager/v1/register/index/php

  • Joey Salac Hipolito

    Uhmm, this will not yet accept cross-origin requests right?

  • ozzner

    helpme please ;(

    404 Page Not Found

    The page you are looking for could not be
    found. Check the address bar to ensure your URL is spelled correctly. If
    all else fails, you can visit our home page at the link below.

    Visit the Home Page

    • basheer

      have checked it with the chrome extension, try it out, it works

  • Paco

    Edited. Everything OK.

  • Ron

    For some reason I cannot download the source of signup (no email received yet). Can somebody zip the entire working project and share it? My son asked me for a good tutorial ans this one looks very good. Thanks in advance

    Ron

    • ian

      That happened with me as well. Just check ur spam email, thats where mine went into

    • DeveloperH

      The tutorial is so clear just flow it, you don’t need the ZIP

  • DeveloperH

    – You need to inizialize $password_hash in the DbHandler Class at line 79
    – Don’t put the require in the constructor, it’s better in the beginning of the class just before
    – Delete the ‘.’ in the require when you include Config.php and DbConnect.php

  • Tim

    Thank you for the tutorial but …

    I do not understand why I get a 500 Internal Server Error :

    – I unzip the archive
    – I placed the folder task_manager on www folder (c:wampwww)
    – I turned on rewrite module in apache
    – I uncommented the line “LoadModule rewrite_module modules/mod_rewrite.so” on C:wampbinapacheapache2.4.9confhttpd.conf
    – always this error 500 Internal Server Error…

    • Mohammed

      Verify your Apache Modules in Wamp Server and Enable the rewrite_module

      • adnan

        make sure to enable the rewrite_module in the php.init. Search google to get full details.

  • Tom

    Thank you for the tutorial but I have some problems

    I have a 500 Internal Server Error, I turned on the module in apache rewrite but I still have this error

    sugestions?

  • Could we use Slim’s http://docs.slimframework.com/#Middleware-Overview (Middleware) technique to authenticate users? I am new to Slim and just trying to have it’s most.

  • Dennis Hatcher

    Great tutorial! I ran into a couple of issues:

    1. needed to change
    include_once dirname(__FILE__) . ‘./Config.php’;
    To:
    include_once dirname(__FILE__) . ‘/Config.php’;
    in DbConnect.php (dropped the dot (.) before the file name). Might have something to do with being in a hosted environment.

    2. Had issues with DbHandler.php. I have mysqlnd, but only the PDO extension (again, hosted environment). All calls using $stmt->get_result()->fetch_assoc(); needed to be re-written. For example the getUserByEmail:

    public function getUserByEmail($email) {
    $stmt = $this->conn->prepare(“SELECT name, email, api_key, status, created_at FROM users WHERE email = ?”);
    $stmt->bind_param(“s”, $email);
    if ($stmt->execute()) {
    $stmt->bind_result($name, $email, $api_key, $status, $created_at);

    /* fetch values */
    mysqli_stmt_fetch($stmt);

    /* set values */
    $user[‘name’] = $name;
    $user[’email’] = $email;
    $user[‘api_key’] = $api_key;
    $user[‘created_at’] = $created_at;

    $stmt->close();
    return $user;
    } else {
    return NULL;
    }
    }

    Thanks again!

    • mannan

      Surerb. Good Alteration. Timely re-written

    • gkm

      Thanks a lot Dennis good point out.

    • Yakup Başer

      right there
      i get an error on tht function:

      Call to undefined method mysqli_stmt::get_result() in /home1/beysplay/public_html/task_manager/include/DbHandler.php on line 268

      public function getAllUserTasks($user_id) {

      $stmt = $this->conn->prepare(“SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?”);

      $stmt->bind_param(“i”, $user_id);

      $stmt->execute();

      $tasks = $stmt->get_result(); <<<close();

      return $tasks;

      }

  • Prateek

    Where is android in this tutorial? This is about a general php server exposing REST APIs..

    • This part explains server side technology when your app is connecting to a cloud hosting server.

  • ALLAN

    This tutorial is Great,!, really helpful..

  • Donny Crash

    Hi there, I really enjoyed this tutorial.. I’ve made some mods to accept JSON / Form Data and for it to work on php 5.4. Do you mind if I post it on github?

    • Yeah you can post. But it will be much appreciated if you can give link back to my blog.

  • ssougnez

    Hi… Awesome tutorial once again. The next step in my app is to use Facebook API. After a small search on Internet, I directly found an article on this website. This is really great.

  • Robin Tyglare

    Hi. Thanks for a very good tutorial. Made me learn alot. But, I would like to send the requests via application:json instead of application:x-www-form-urlencoded, but I just cannot make it work. Please give me a push in the right direction 🙂 I’m realy stuck here. Anyone help?

    • Chandan Singh

      just used

      $app->request->getBody();

      to extract ur json instead of

      $app->request->post(param);

  • Florian Kirschna

    Very nice tutorial, but I’m missing the point where you secure your registration method. I mean it would be really easy for a spammer to take advantage of this, or am I missing something here ? What is the industry standard for this ?

  • Raja

    Hi . Thanks for the tutorial.

    Why do I keep getting “Unexpected token C” -> JSON Tab when testing with the Advance Client Rest ?

    However I can see the registered succesful message in the Raw tab.

    Thanks

    • Adnan

      This happens if you’re echoing something in the script. Remove all echos.

      • Guest

        I have the same problem and the only echo in the index.php script is this

        echo json_encode($response);

        which i think is the one that should be there (since i’m using the download copy of the project). does any body knows if there is something else to review?

  • Adnan

    Ravi,

    Amazing tutorial. Helped me understand REST services clearly.

    One part of the code I don’t understand though:

    $new_task_id = $this->conn->insert_id;

    What is this insert_id? Is it a variable, function, where did it come from?

    • Adnan

      Another question, do we need the relation table? can’t we achieve the same result by adding a FK column in the ‘tasks’ table?

      Thanks again

    • The is the mysql row id (primary auto increment value) of last inserted row. i.e the current row that is you just inserted.

  • Amazing Tutorial, Now I came to understand that how to integrate Slims library to develop my PHP projects, Would like to know whether this help in android app development. Also I learnt interesting things here http://bit.ly/1dhMAqu
    http://bit.ly/1mgMn8D

  • avinash kumawat

    Great job ravi its help alot 🙂 but got 404 error code rewrite module is enable already , don’t know why this give 404, plz help me out

  • Rendy Setya Pratama

    Hello Ravi,
    btw thanks for stunning tutorial !

    I have one problem when test the API in google chrome.

    The problem is :

    Fatal error : Call to a member function bind_param() on a non-object in C:xampphtdocstask_managerincludeDbHandler.php on line 113

    Can you help me ?

    Thanks 🙂

      • Rendy Setya Pratama

        Thanks for another response 🙂

        btw, you say that you do not continue part 3, actually what the contents of the tutorial in part 3?
        because I’m developing a restful API for my project and Your Tutorial help me a lot.

        I just feeling curious.

        Thanks 🙂

        • Third part is about hosting the code on a real server like bluehost, hostgator. I wanted to explain how to buy a server, host the files, configure the server and expose the services to public. But after finalizing everything I got a problem in verification. That is why I stopped posting that part.

          • Rendy Setya Pratama

            Thanks for your fast and friendly response 🙂

            I have a last question for you, may I ?

            I told you before that I’m develope a RESTful API for my project right now.
            Mobile as client and Website as server.

            But I don’t know how to make the RESTful API (from your tutorial) work with Mobile (as Client) and Website (as Server).

            Can you tell me the steps ? (only the steps not the code)

            Your answers really help me.

            Thanks :).

  • lightingwang

    Hello Ravi,
    thx for your tutorial!!
    I want use it to transfer data with android device.
    But i am just a beginner..
    if you are not busy, Can you make another tutorial about how to use android device to connect to restful server via php, json and mysql…
    I try it but it is so hard T.T
    Thanks~~~~

    • Chandan Singh

      if you want to extract json just use

      $app->request->getBody();

      instead of

      $app->request->post(param);

      • Rico

        Hii Chandra it does not work. i put that in api, and test it on chrome rest client and set “content-type: application/json”. Getting this error “Trying to get property of non-object”
        i do like these
        $json = $app->request->getBody();
        $json->email;
        $json->password;
        Can you help me?

    • narendra nauth

      There is a great tutorial on Lynda.com for this

  • Michael

    Hi,

    Good tutorial, thank you very much Ravi.

    I try it on WAMP and on LAMP and on two of us, I’ve always got the 400 Bad Request error but I try the same thing you. I don’t understand.

    My test:
    http://localhost/task_manager/v1/register
    Method: Post
    No header
    name: Michael
    email: michael@test.com
    password: chocolate

    And I’ve got this:
    {
    error: true
    message: “Required field(s) name, email, password is missing or empty”
    }

    I’m really discomfit, and I see nothing in log that could help me.

    Finally I succeed to register one user in database (manually) and try to login with this user with api key etc.. but I still have the same issue (Bad request: “…email, password is missing or empty”)

    info => I think the api key is well recognized because if I remove it I’ve got the message: “api key is missing”

    If someone had the same problems or hase some solutions to offer me, I will be grateful to him for helping me.

    Thank you. Bye

    • mani

      i am getting the same thing, did you fix it? does it work now?

      • narendra nauth

        I dont believe you are passing the params correctly. Attach the exact code you are using so assistance can be provided

        • brokenOval

          Also getting the same problem my side, the code as follows:

          $app->post(‘/test’, function() use ($app) {
          // check for required params
          verifyRequiredParams(array(’email’));
          echo “Success”;
          });

          And the verifiyRequired params is unchanged from the original:

          function verifyRequiredParams($required_fields) {
          $error = false;
          $error_fields = “”;
          $request_params = array();
          $request_params = $_REQUEST;
          // Handling PUT request params
          if ($_SERVER[‘REQUEST_METHOD’] == ‘PUT’) {
          $app = SlimSlim::getInstance();
          parse_str($app->request()->getBody(), $request_params);
          }
          foreach ($required_fields as $field) {
          if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) stop();
          }
          }

          It seems to be breaking on the line $request_params = $_REQUEST; where no data is being passed from the REST params

          • narendra nauth

            Try this:
            ‘var email;

            $.ajax({
            type : ‘POST’,
            beforeSend: function (request){
            request.setRequestHeader(“Authorization”, “YOUR_AUTH_STRING”);
            },
            url : ‘v1/test’,
            data : ’email=’ + email,
            success: function(response){
            console.log(response);
            }
            });

            And make sure you are passing a value in the email variable.

    • sage

      I have the same problem with the api……………..who has a solution to it pls?

  • John

    Hi,

    This is a really great tutorial. But just wanted to point out regarding the “Authorization” code. If you are hosting the php code on some shared hosting you might want to change the name of the field to something else.

    Because i have encounted problem when passing the Request Header with the field as “Authorization”. The Apache server will remove it and hence the server code is not able to find it.

    After asking around it seems that it is because the “Authorization” is uses as a special keyword for the Apache authorization system. Any other header key would be valid, but authorization is stripped off and not passed to PHP when running as CGI in suexec mode. You might want to change the authorization key name to something different.

    Hope this will help.

  • Very Nice, Thank’s

  • chaitu

    i am getting 404 error…tried everything…help me

    • chaitu

      working now thanq..

      • mani

        what was the problem?

      • stralo

        Hey Chaitu, how were you able to get it to work. I’m working on a mac with Poster and I’m getting a 404, too. I went through index.php, commenting stuff out and realized it’s caused by the line $app->run.

        Did you have the same problem? And if so, how did you fix it?

        Thanks!

  • enti

    About “Authorization” problem. Not only server removes “Authorization” header, it capitalizes every word. For example it will change “authorization-key” to “Authorization-Key”. Solution is to enter a header with capitalized letters.

  • Md Ali Azhar

    PassHash Class is USELESS.
    Starting in PHP 5.5, a new API for hashing passwords is being introduced:

    1. To generate hash -> password_hash($password,PASSWORD_BCRYPT);
    -> DEFAULT CostParam=10,
    -> PASSWORD_BCRYPT is used to create new password
    hashes using the CRYPT_BLOWFISH algorithm
    -> password_hash generate the salt randomly for you

    2. To verify hash -> password_verify($password, $hash)

  • Claudio

    It’s missing a method in order to delete an user from table ‘users’ including also the automatic deleting of user’s tasks associated with this method.

    • narendra nauth

      You can easily write this method. What he did was jus to show an example oh how to use it

  • Tiago Pereira

    Hi.
    how can i introduce login with facebook on this great app?

  • mani

    Hi Ravi,
    First thing first, thanks for the awesome tutorial, this is best.

    I have a Android project for school, so I decided to use RESTFULL api, I’m running and hosting my server on aws(amazon web server). when I tried to check if everything work and get a right result back as a jason in “Advance Rest Client” I got 404 error

    404 Not Found

    Not Found
    The requested URL /go_club/v1/register was not found on this server.

    can you help me why it cannot find …/register ?

    Thanks

    • Riko

      Same here, i try to test in my android app it does not work. Did you solve that issue?

      • mani

        not yet 🙁

    • narendra nauth

      You cannot access that route directly. You have to send required params using POST to that route. You can do this easy with AJAX

  • Fuck SQL

    To anyone getting 500 internal serve error my solution was to drop the anonymous user in the database!

    • Rafael

      How to fix error 500?

  • Gokalp

    Super! Thanks a lot..

  • pera

    Ok, can someone show how frontend JS ajax call will looks like?

    • narendra nauth

      This is an example for the register:

      var name = $(‘#name’).val();
      var email = $(‘#email’).val();
      var password = $(‘#password’).val();

      $.ajax({
      type : ‘POST’,
      data : ‘name=’+name+’&email=’+email+’&password=’+password,
      url : ‘v1/register’,
      success: function(response){
      //Process based on response
      }
      });

    • narendra nauth

      Example of create task

      $(‘#create-task’).click(function(){
      var task = $(‘#task’).val();
      $.ajax({
      type : ‘POST’,
      beforeSend: function (request){
      request.setRequestHeader(“Authorization”, “YOUR API KEY”);
      },
      url : ‘v1/tasks’,
      data : ‘task=’ + task,
      success: function(response){
      console.log(response);
      }
      });
      });

  • so much thanks!

  • Pablo

    I can’t get this example to work, I keep getting error: 500 Internal Server Error. Any ideas? thanks!

    • Pablo

      Sorry, I hadn’t enabled mod_rewrite, problem solved.

      • reza

        hi please tell me how do you enable mod_rewrite?
        thank

        • Pablo

          Apache – Apache Modules – select Rewrite module

          • Darren Jones

            Just for info, this is in Wamp in the System tray, left click to get Apache, then Apache Modules

  • william

    Hi Ravi, Thanks for the tutorial. I managed to set up a REST api following your tutorial and its working fine. Am able to fetch data but i have failed to Post data with parameters to it using volley library (android) i get an error BasicNetwork.performRequest: Unexpected response code 400 for http://192.168.1.105/my_api/v1/register. I have tried most of the solutions online but non seems to work. below is the code am using

    final ProgressDialog pDialog = new ProgressDialog(this);

    pDialog.setMessage(“Loading…”);
    pDialog.show();

    // uploade here
    JsonObjectRequest jsonReq = new JsonObjectRequest(Method.POST,
    URL_REGISTRATION, null,
    new Response.Listener() {

    @Override
    public void onResponse(JSONObject response) {
    Log.d(TAG, response.toString());
    pDialog.hide();
    }
    }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {

    VolleyLog.d(TAG, “Error: ” + error.getMessage());
    pDialog.hide();
    }
    }) {

    /*
    * parsing parameters
    *
    * @see com.android.volley.Request#getParams()
    */
    @Override
    protected java.util.Map getParams() {

    java.util.Map params = new HashMap();
    params.put(“name”, name);
    params.put(“email”, email);
    params.put(“gcm”, regId);

    return params;
    }

    /**
    * Passing some request headers
    * */
    @Override
    public java.util.Map getHeaders()
    throws AuthFailureError {
    HashMap headers = new HashMap();
    headers.put(“Content-Type”, “application/x-www-form-urlencoded”);
    return headers;
    }
    };

    // adding request to volley request queue
    AppController.getInstance().addToRequestQueue(jsonReq);

  • Hi Ravi, this is such a nice tutorial. It has worked fine using chrome advanced Rest Client. But i would like to use this via URL..for instance; /v1/register with POST method to add new user to db via My browser URL.How can i go about?Just need a sample URL format demonstrating how to register new user.

    • You can’t do POST via browser url. You can create a simple HTML form and use the post url to demonstrate.

    • narendra nauth

      As what he said you can simply use a form with name, email and password and set action=”v1/register” for your form and it works fine.

  • mirageservo

    Hi Ravi, you made a very nice complete yet detailed REST example here, its a very interesting stuff, I have tried this and worked with little to no problem on my dev/local deployment. I have a little problem though, first I want to verify if I try to access the route in the browser, (login route) what should I see, a 404 or a valid json response? Currently, I always get a 404 albeit if I throw in a POST request using a REST client I am able to receive a response, am I doing something wrong?

    • narendra nauth

      You cannot access that route directly and have a response. You must send he required params to that route using a form via AJAX or any other method you decide to.

      • mirageservo

        Hi narendra, if I understand you’re message correctly, does that mean, even using Firefox “POSTER” nor Chrome’s “Advance Rest Client” will not work?, likewise, you’re telling me that I’m sending not a valid param format?, anyway, I’ll try your AJAX advise and see if it fixes my error/s.

        • paijopkl

          maybe mirageservo do not place $app->run(); in the end of index.php,

      • mirageservo

        Hi narendra, I have tried sending the params via ajax, and unfortunately, it does not fix my problem, it only yields “an empty string” response, this is starting to crack my head…. could it be the host? but I’ve checked it, and mod_rewrite is enabled, are there anything else I need to consider/reconsider?

  • mirageservo

    I also noticed, if I change the request from post to get such as $app->post(‘/login’, function(){}) into $app->get(‘/login’, function(){}, I’m able to view the response on the browser, I’m getting an understanding of the whole picture though having some little greyed area, Is that because I didn’t send the post key pairs (as there is no way to do that in the browser)?

    • narendra nauth

      Send them using AJAX

  • sureshh testing

    i have tried but responses “Response does not contain any data.”

  • Führer Saleh Mashal

    hi can any one helping me when i do registration for new user it is give me 404 not found how can i fix it. please help me

  • Maw

    Hi, firstly, thank you for nice tutorial how to restful api with slim framework. But I want to do it other way and don’t know how to start. I don’t want users to register but still I don’t want API totally open (so I don’t want that anybody should go to url and get response from server for example from browsers or any external apps). How I can implement something like self-registration of device based on something unique (like device ID?). I don’t want to store any user identity details but still I want to control access to my api to be sure that only from my android app (or basically only from my mobile, web, any apps) will be api accessible? Thank you in advance for any suggestions.

    • narendra nauth

      This can be done with the use of setting the authenticate function on all your methods. You can manipulate it to work with an API username and API key. This will allow you to control access as you desire.

  • kiran

    I think you should add one line after every json response heading.

    ” add following code before app->run() ”

    btw very nice tutorial..
    Thank you !!

  • kiran

    Modify following 2 files
    ——————————–
    1. DbHandler.php

    require_once dirname(__FILE__) . ‘./DbConnect.php’;

    to

    require_once dirname(__FILE__) . ‘/DbConnect.php’;

    2. DbConnect.php

    include_once dirname(__FILE__) . ‘./Config.php’;

    to

    include_once dirname(__FILE__) . ‘/Config.php’;

    just remove .(dot)

    • Jason

      Yes! This fixed my issue. Thank you!

    • Kim Jansson

      Doing this + moving $app->run() to the bottom of index.php did the trick for me. Thanks a lot!

  • Giuseppe Scordo

    Congratulations for your article. has been very useful for my project. When you publish the third part? Thank You

  • Stephen

    Hi,

    Two points.

    1) using uniqid() to create random #s is explicitly discouraged by the php docs: http://php.net/manual/en/function.uniqid.php

    2) using password_hash() (http://php.net/manual/en/function.password-hash.php) is encouraged for hasing passwords.

  • Mustafa

    Please help. When I test “http://localhost/task_manager/v1/tasks”, I am getting “Api key is misssing”.

    • narendra nauth

      That is displayed because in the authenticate method, there is no $headers[‘Authorization’]. You need to pass that within the ajax like the example below:

      $.ajax({
      type : ‘GET’,
      beforeSend: function (request){
      request.setRequestHeader(“Authorization”, “YOUR_API_KEY”);
      },
      url : ‘v1/tasks’,
      success: function(response){
      //Process your success
      }
      error: function(jqXHR, textStatus, errorThrown){
      //Process your error
      }
      });

  • Saurabh Singla

    can you explain is it possible to send HTTP Post request to slim restful api from android? if yes than how ?

  • Dimitrije Randjelovic

    Just wanted to ask if anyone knows or wants to know…
    How would you get all the tasks for one user ? I thought this could be made as a simple social app.
    For example, if you change each work ‘task(s)’ into ‘status(‘s)’ it would be nice to have ‘profile’ where you use getallUSERstatus and a home feed with getALLstatus if you understand me, i am not quite good at MySQL but if there was an example i could learn a bit more and more. Thanks in advance

  • jb patel

    Thanks for this ….How Can i will use this REST api in android replay fast

  • Alois Napitalai

    Cant get this to work in ubuntu,nothing is displayed when I try to access http://localhost/task_manager/v1/tasks

  • marrocmau

    Hi, great work! I tried it in my local LAMP system it’s works fine (I tried all kind of services) BUT when try to use it in personal website (ex: http://www.example.com) i have a problem with Authorization field…it is as though this parameter is not passed to the service (i used “Advanced Rest client” “Postman” and “DHC” -chroms’ apps- for test the Rest service).
    Somebody can help me?

  • Kinza Rian

    thanks !

  • dazziep

    if I miss API key on purpose, I get “Api key is missing” as expected (awesome 🙂 ) BUT I get HTTP status 200, I seem to get 200 for everything, successful or not ???

    • YourBro

      change the methode you use and add in case of faillure echoRespnse(“NEW CODE”, $response) if u see what i mean it will answer with a new http code in case other conditions does not meet, i hope iv helped

    • You can do it in two ways.
      1. Keep the 200 and while parsing the json check for error flag.

      2. Modify the code and use ‘401 – access denied’ when api key is missing.

  • great tutorial

  • Mário Ramos

    Hi Ravi!
    First, thank you for such a nice tutorial.
    Second, not really related to the intent of this project, but if I had the need to connect to different databases (MySQL, SQL Server, etc, via PDO) depending on the route called, what modifications to DBConnect and/or DBHandler and the methods would I need to perform? I’m still a noob in OOP. Thanks!

  • Alex

    I’ve followed all the steps and copied all the files but when I come to test it with the chrome app I do alway get a 404 not found… can’t find out whats wrong :S… some help would be apreciated.

    Thanks

    • VerSo

      Look at your htaccess file. Maybe you have another file in that directory. Try on public html folder. For example domain test.net you can try to put your files on root directory regullary public_html.

  • Nguyễn Huy

    Hi Ravi!
    Thank you for such a nice tutorial.
    I have anh error when i GET tasks “Fatal error: Call to undefined function apache_request_headers()”

    Can you help me?
    Thanks you!

    • Parmendra Singh

      Please check your php version. PHP 5.4.0 and later support this function.

  • Gaston

    Is there any tutorial on how to use the REST API from my Android applicantion?

  • VerSo

    For all that get 500 error check PHP version to be 5.3 or greater.
    For all that get 404 check that method corespond: what you send and what the server wait POST -POST for example.
    Check twice, for example register page need post in rest client.

    • Halima Elboulali

      i have the 5.5.12 as version of php and still have 500 error ! any other suggestions plz

      • VerSo

        try to reinstall all again
        you run this on your own local hosting? like xamp?
        I try to install on my webhoting and it didn’t work because my hosting provider have allot of exceptions, so after that i installed xampp on my computer and all work ok

        For final proposes you can try digitalocean for 5 bucks!

        you can contact me at verso . 930@gmail . com for help

  • Guest

    Any method in index.php has to be above $app->run(); this solve problem with 404.
    .htaccess should be in dir where index.php is located.

  • Aurelian N

    Hello, nice tutorial,

    I just put your example on a debian server and it seems that on showing all tasks i get an error , if i look on the server error log i get :

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP Fatal error: Call to undefined method mysqli_stmt::get_result() in /var/www/sites/rdvapi/include/DbHandler.php on line 268

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP Stack trace:

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP 1. {main}() /var/www/sites/rdvapi/v1/index.php:0

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP 2. Slim\Slim->run() /var/www/sites/rdvapi/v1/index.php:339

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP 3. Slim\Middleware\PrettyExceptions->call() /var/www/sites/rdvapi/libs/Slim/Slim.php:1254

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP 4. Slim\Middleware\MethodOverride->call() /var/www/sites/rdvapi/libs/Slim/Middleware/PrettyExceptions.php:67

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP 5. Slim\Middleware\Flash->call() /var/www/sites/rdvapi/libs/Slim/Middleware/MethodOverride.php:92

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP 6. Slim\Slim->call() /var/www/sites/rdvapi/libs/Slim/Middleware/Flash.php:85

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP 7. Slim\Route->dispatch() /var/www/sites/rdvapi/libs/Slim/Slim.php:1307

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP 8. call_user_func_array() /var/www/sites/rdvapi/libs/Slim/Route.php:436

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP 9. {closure:/var/www/sites/rdvapi/v1/index.php:141-163}() /var/www/sites/rdvapi/libs/Slim/Route.php:436

    [Tue Mar 31 09:15:08 2015] [error] [client 192.168.88.50] PHP 10. DbHandler->getAllUserTasks() /var/www/sites/rdvapi/v1/index.php:147

    Can you please help me with that .

    Thanks in advance

    • Aurelian N

      Anybody ?

      Regarding ,

      Elroy Shilling

      On line 268

      Change this:

      $tasks = $stmt->get_result();

      To

      $tasks = $stmt->bind_result();

      that part does not work, it generates more errors :

      Slim Application Errorbody{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}Slim Application ErrorThe application could not run because of the following error:DetailsType: ErrorExceptionCode: 2Message: Wrong parameter count for mysqli_stmt::bind_result()File: /var/www/sites/rdvapi/include/DbHandler.phpLine: 281Trace#0 [internal function]: SlimSlim::handleErrors(2, ‘Wrong parameter…’, ‘/var/www/sites/…’, 281, Array)
      #1 /var/www/sites/rdvapi/include/DbHandler.php(281): mysqli_stmt->bind_result()
      #2 /var/www/sites/rdvapi/v1/index.php(147): DbHandler->getAllUserTasks(2)
      #3 [internal function]: {closure}()
      #4 /var/www/sites/rdvapi/libs/Slim/Route.php(436): call_user_func_array(Object(Closure), Array)
      #5 /var/www/sites/rdvapi/libs/Slim/Slim.php(1307): SlimRoute->dispatch()
      #6 /var/www/sites/rdvapi/libs/Slim/Middleware/Flash.php(85): SlimSlim->call()
      #7 /var/www/sites/rdvapi/libs/Slim/Middleware/MethodOverride.php(92): SlimMiddlewareFlash->call()
      #8 /var/www/sites/rdvapi/libs/Slim/Middleware/PrettyExceptions.php(67): SlimMiddlewareMethodOverride->call()
      #9 /var/www/sites/rdvapi/libs/Slim/Slim.php(1254): SlimMiddlewarePrettyExceptions->call()
      #10 /var/www/sites/rdvapi/v1/index.php(339): SlimSlim->run()
      #11 {main}

      • praditautama

        your server doesn’t have “get_result” function. Try to modify DBHandler.php using PDO statement.

        • kartik

          how?

  • I added the following to my .htaccess file to solve the “Api key is misssing” error:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]
    RewriteCond %{HTTP:Authorization} .+
    RewriteRule .* – [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    • lernrr777

      @elroyshillingit:disqus Hey thanks for this. I faced the same issue and tried alot this fix solved my problem.

  • Scrobie Ballstein

    Hey! When I create a task I get the error : execute() failed: Column ‘user_id’ cannot be null.
    My task is created in tasks table but user_tasks table is empty.
    Can someone help?

  • Trey Rosius

    I keep getting this error, any Help!! please

    Fatal error: Class ‘PassHash’ not found in C:wampwwwtask_managerincludeDbHandler.php on line 35
    With a status code of 200 OK

    • Trey Rosius

      solved

      • kartik

        Can you help? POST and PUT Methods are not working..

    • Stark

      I stuck in problem. I used Advance Rest Client. Status code of 200 OK but cannot register..

      I also type in URL: http://localhost:8080/task_manager/v1/register.

      The error notied: Parse error: syntax error, unexpected ‘$error’ (T_VARIABLE) in C:wampwwwtask_managerv1index.php on line 15

      Can you help me solve this problems?

  • praditautama

    Nice tutorial! Unfortunately it doesn’t work on my server because my server doesn’t have MySQL native driver. “get_result” causes 500 internal server error.

    I managed to modify using PDO and it works now

    • Abhishek Rohilla

      can you please share the code for PDO?

  • Trey Rosius

    user_id remains 1 and never changes in table user_tasks, even though i use different users to create tasks.Does anybody know how to fix this.
    ->task_id responds well.

    • Scrobie Ballstein

      Hey! If you look below you’ll se my question; my code is exactly the same as Ravi’s but it still doesn’t work.
      Any idea?

  • Rico

    why i cant post data in “Content-type: application/json” format even change to this in webservice
    $post_a = json_decode($app->request()->getBody());
    $post_a->email;
    $post_a->password;

    Test it on Chrome advance rest client app.

  • Barefoot

    Hi,

    Thanks for great tutorial.

    I use this in server apache and everything else is working but
    …./v1/tasks (Get all tasks) is NOT
    even
    …api/v1/tasks/1 (get single task) is working and login and register etc.. is working great.

    I get 500 error like this with …./v1/tasks [GET with API KEY]

    Date: Fri, 10 Apr 2015 10:19:45 GMT

    Server: Apache
    X-Powered-By: PHP/5.4.19
    Cache-Control: max-age=2592000
    Expires: Sun, 10 May 2015 10:19:45 GMT
    Vary: Accept-Encoding,User-Agent
    Content-Encoding: gzip
    Content-Length: 20
    Content-Type: text/html; charset=UTF-8

    Response does not contain any data.

    Can anybody hep??

    • praditautama

      Make sure your server support for “get_result” function in mysqli

      otherwise, you must change to PDO function like i did

      • kartik

        Can you help? POST and PUT Methods are not working.

    • Sandeep Reddy M

      Did you solve 500 error. For me also getting 500 error, even Service in ON

  • Aurelian N

    Hello guys,

    you have here the working code, i don`t know if the .htaccess file exists in the v1 folder but the rest is there, tested and validated.

    https://www.dropbox.com/s/kift276d75f4ew3/working%20code.zip?dl=0

    • Scrobie Ballstein

      Thanks Aurelian! This code works perfectly

      • kartik

        Can you help?? POST and PUT Methods are not working.

        • Scrobie Ballstein

          You have Error 500?

    • kartik

      It is not working on localhost as well as on server.

    • Sandeep Reddy M

      Giving 404 error for that drop box link

    • vishakha

      how can I run register url. Please help anyone can I have whole index page

  • kartik

    Getting error.
    500 Internal Server Error

  • kartik

    Can any one help? I’ve downloaded the above mentioned code but it is not working on my localhost.
    Even on a server it’s not working.
    P.S: in include folder there is one file called DbHandler.php, When I try to on server. It get deleted automatically. Is there any reason behind that?

  • kartik

    Ravi Tamada Plz help

  • kartik

    Ravi Tamada

  • Rendy

    Hy Ravi
    Can you help me, I get some error

    Notice: Undefined variable: app in C:xampphtdocstask_managerv1registerindex.php on line 8

    Fatal error: Call to a member function post() on null in C:xampphtdocstask_managerv1registerindex.php on line 8

    $app->post(‘/register’, function() use ($app) {

  • kartik

    For every post request, following message is displaying.
    Please help.

    message: “Required field(s) task is missing or empty”

  • kartik

    Get and Delete method is working. Post and PUT method is not working. Please help

  • Greate Tutorial!!! 🙂

    I also had a Problem with the code.

    It cuold not load the DbConnect.php from DbHandler.php . The reason was in this part of code:

    include_once dirname(__FILE__) . ‘./Config.php’;

    the ‘.’ in ‘./Config.php’ was making a wrong path: /tasks/include./DbConnect.php

    By removing the ‘.’ in ‘./Config.php’ it worked again. So that the code looks like this:

    include_once dirname(__FILE__) . ‘/Config.php’;

  • Sandeep Reddy M

    Unable to run. Wamp is successfully installed and downloaded source and copied to www/taskmanger
    But when I test Chrome Rest Client giving following error. Please help me

    Status
    500 Internal Server Error Loading time: 8
    Request headers
    User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
    Content-Type: text/plain; charset=utf-8
    Accept: */*
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-US,en;q=0.8
    Response headers
    Date: Sat, 25 Apr 2015 03:48:19 GMT
    Server: Apache/2.4.9 (Win32) PHP/5.5.12
    Content-Length: 614
    Connection: close
    Content-Type: text/html; charset=iso-8859-1

  • Mo’nes Qasaimeh

    how to call register function from index.php plz help me

  • Nguyễn Huy

    Hi Every one!
    I need project android sample rest api above. Please share for me. Thank!

    • Nguyễn Huy

      Please help me !!

      • Trey Rosius

        @disqus_qvQOzHG2Wq:disqus . look closely at the implementation of the tutorials”Android login and Registration using Mysql, PHP and also the tutorial on the paypal rest api”.That should be enough to show you vividly how to build your REST APP.You will have to sweat a lil bit.That’s aitt.Everybody does.That’s how i did mine.Everything is on this site.
        Rescue yourself.
        Good Luck

        • Nguyễn Huy

          thank you!

  • Able Alias

    Hi,
    Please answer any one for this question, my question is how this statement gets the API key $headers[‘Authorization’]
    $api_key = $headers[‘Authorization’];
    in function authenticate, when I check I’m getting “null” value

    Ohh… yes, I got it. I was not send Authorization request header in the post call.

  • Alex

    ok so I get it that API is ready, now how do I use this data in android device. is there any body parser you would recommend? or any other good options u got ?

  • Alex

    ok so I get it that API is ready, now how do I use this data in android device. is there any body parser you would recommend? or any other good options u got ?

    • Kien

      Please sent me your code, I’m stucking in this tutorial and I don’t know why.

      When I changed file .htaccess to .htacess and type url:

      “http://localhost:8080/task_manager/v1/login”
      There was 500 error:
      .

      But when I changed .htacess to .htaccess, It will not error

      But it turn to The requested URL /task_manager/v1/login was not found on this server.

      Please help me.
      Thank you

  • simple gats

    hei Ravi.. how to upload image/file using slim framework ?

  • Rodrigo Vieira da Costa

    Hi Ravi! Thanks for this example! you can help us create a sample android app using this api php and mysql slim, with CRUD? Thanks!

  • MelDiSooQi

    Really Nice tutorial Ravi Tamada

    but i think it’s missing something. it’s missing the third part and you
    should do this tutorial for it. it’s a android Part i hope to explain
    how can send and receiver from android application with Rest(Slim)
    hope to make short example to use it in android application soon just short example

    and thank you very much for all you do you are the best

  • Alois Napitalai

    Can someone please help, i am getting 400 bad request,required fields password ,email and name are missing or empty when I try to register via poster/Chrome rest client

  • Stark

    What if I want to comment in single task.
    How can I do that ?

  • rocky

    Creating Magento Website Android Application.I know Magento provides SOAP/REST APIs to use it into our app to call the products/user login/etc. Any tutorial on this topic.

  • Thank you for the great tutorial

  • hamid khaksar

    Thanks a lot for this tutorial , if anybody getting Error 500 , not to worry 🙂 To solve this problem was Check that you have the the apache rewrite module loaded.

    go to wamp_manager -> apache -> modules and look for rewrite_module in the list.

    If it does not have a TICK beside it click it. Apache will be bounced ( stop, start ). Try again.

    The rewite engine will not work without the required module loaded.

    • Thanks Hamid for pointing that out 🙂

      • hamid khaksar

        You’re welcome 🙂

  • Sadam Hussian

    Hi guys! I want android code to perform these actions . Can somebody help me? Its urgent……!

  • Nicolas Bourdin

    Hi, thanks for this tutorial.
    I have a problem,
    Then I try to make a request (like http://localhost/www/task_manager/v1/tasks) it display
    {“error”:true,”message”:”Api key is missing”}

    And when i make the same request with Advanced Rest Client i got a 404…

    Someone know what is the problem plz?

    Thanks in advance

    • Andrew Nyago

      I have a similar setup. How did you get to that error please? what did you change?

      this is what i’m getting now:
      The requested URL /androidchatter//task_manager/v1/tasks was not found on this server.

      from:
      http://localhost/androidchatter//task_manager/v1/tasks

  • Erwinson Pagtalunan

    Hey Ravi,
    I’m having a small problem from your code which I have already fixed myself.
    I will just ask about it (because others said in the comments that its working, but not in mine).
    This part of code when creating the middleware function:

    function authenticate(SlimRoute $route) {

    Can I ask why there is a parameter (SlimRoute $route) on it?
    It does not work in me. I don’t know why.
    Also, when reading this part, I’m asking myself why this parameters are needed.

    So then when I test my application, it does not give any output.
    I even tested non-existent routes in my app but it does not give the “Page not found” error pages. I have also enabled debug in Slim’s settings but still no output. Then I removed this parameter and everything now works.

    Thank you Ravi! Very good tutorials as always.

    Edit:
    Some follow up question:
    I’ve decided to make the index.php file slim (less lines) by migrating some controller functions on other classes.
    For example, I moved the functions the app will call on the /api routes to a class called Api.
    With that, I placed my “authenticate” middleware function there as a static function, so it is now Api::authenticate.
    My question is, how will I put that as a middleware in a route call?
    I tried doing:
    $app->get(‘/foo’, ‘Api::authenticate’, function() { ……..});
    $app->get(‘/foo’, Api::authenticate(), function() { ……..});
    to no avail.
    Please help. Thanks as always!

    Edit again:

    Sorry! My bad. Working now.
    Looks like callbacks always need the fully qualified class name (I use namespaces) even though I declared to use just ‘Api’.
    The solution for me is:

    $app->get(‘/foo’, ‘SomeNamespaceApi::authenticate’, function() { ……..});

    —————-

    My question now will just be the first one (about the parameter).

    Last Edit (hopefully):
    I have read about my question on the docs.
    I didn’t know why I haven’t saw it earlier while reading it.
    Thanks! Problem solved! Your tutorial was great. It was me that has a problem. (the namespace things).
    Thank you for this.

  • Ram Shrestha Shikarin

    how show the users from database in advanced Rest clients

  • Helge Larsen

    Running on PHP version 5.4
    I am trying this webservice, but I seems to have the problem that the Authorization header is not found (returning “Api key is misssing”)
    I have tried changing it to Xxx (edited the 2 places in function authenticate), and then it works.
    Who or what is stripping the Authorization header?

    • Helge Larsen

      It seems Apache server is stripping the Authorization header, because it is not in the expected format.

      I found a solution on the net: Include these 2 lines in .htaccess file after an empty line:

      RewriteCond %{HTTP:Authorization} ^(.*)
      RewriteRule .* – [e=HTTP_AUTHORIZATION:%1]

      • Arif VirKill Yulian

        Thanks for posting this. you are real MVP

  • odai derawi

    great tut man thank you alot
    but i`m need to know how to connect this php code and server with my android app (the android code that work with this code) and thank you so much << sorry for my english

  • smit shah

    Hi Ravi,

    Thanks for the tutorial.

    I am trying to test the API using Advanced Rest Client extension as you suggested.

    It is giving an error 500 Internal Server Error-Response does not contain any data.

    I am using MAMP.

    Please suggest what could be the problem.

    • Aadesh Shrestha

      In WAMP I solved it by enabling the rewrite_module in apache.

  • Rohit Shrivastava
    • Richmond Alake

      As there been a solution to this error?

      • Seems mod rewrite module is not enabled in php.ini

        • Jose_Mendoza
  • GK Kohli

    Hi Can you post rewrite rule for nginx

    • Jose_Mendoza

      I got it to work with this. Just put it in the server block.

      rewrite ^/task_manager/v1/([^/]+)/?$ /task_manager/v1/index.php?method=$2? last;

  • sagar

    Hello Ravi ,can you please give an example of java program to call REST web-service with POST data..??

    • Jonathan

      Yes would be nice with an example of android program to it 🙂

  • Jonathan

    Is it hard to implant this REST API into this tut you made ? : http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite

  • Thanx Ravi ! i really learn a lot from your awesome posts, from android-php-mysql connect, Google + sign in, Integrating PayPal, Integrating Push with Parse, How to use Volley, and Login tutorial, so i just wanna say thank u very much 😀 *this is my first comment on your site hehe*

  • i made a necessary changes in rewrite module but still i got 404 error while register call

    • sankalp bhambri

      Hi,

      please read my comment above

  • Andrew Nyago

    this is my dirstory structure:

    /androidchatter/task_manager/v1

    whatdo i need to change to get out of the 404 requested URL Not Found error?

  • Andrew Nyago

    I think my Problem is that slim isn’t installed properly and no one gives the full instructions for a beginner.

  • Eranga

    Hi, Thanks for the great post. It works well on localhost WAMP, but when hosted on PHP CGI it does not take the value Authorization. Added RewriteRule .* – [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] and when this is done, without the authorization key, data gets updated. Any help around this?

  • Ilan

    Hello,
    This code is working with old version of Slim.
    Someone has code that works with Slim 3.0.0?

  • vishakha singh

    Notice: Undefined variable: app in C:xampphtdocsmarammut_newv1index.php on line 53

    Fatal error: Call to a member function post() on a non-object in C:xampphtdocsmarammut_newv1index.php on line 53

    not able to register plz share index.php

  • Lon Ilesanmi

    If your getting an error with $stmt->get_result, it may be because of this:
    it works only with mysqlnd driver (http://us2.php.net/manual/en/mysqli-stmt.get-result.php). Solve it by using this:
    DbHandler.php:

    /**

    * Fetching all user tasks

    * @param String $user_id id of the user

    */

    public function getAllUserTasks($user_id) {

    $stmt = $this->conn->prepare(“SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?”);

    $stmt->bind_param(“i”, $user_id);

    $stmt->execute();

    $stmt->bind_result($id, $task, $status, $created_at);

    $tasks = array();

    while($stmt->fetch()) {

    $tmp = array();

    $tmp[“id”] = $id;

    $tmp[“task”] = $task;

    $tmp[“status”] = $status;

    $tmp[“createdAt”] = $created_at;

    array_push($tasks, $tmp);

    }

    $stmt->close();

    return $tasks;

    }

    and in index.php:

    /**

    * Listing all tasks of particular user

    * method GET

    * url /tasks

    */

    $app->get(‘/tasks’, ‘authenticate’, function() {

    global $user_id;

    // global $logger;

    $response = array();

    $db = new DbHandler();

    // fetching all user tasks

    $result = $db->getAllUserTasks($user_id);

    // $logger->info(“A result returned was::”.$result);

    $response[“error”] = false;

    $response[“tasks”] = array();

    array_push($response[“tasks”],$result);

    echoRespnse(200, $response);

    });

  • Carlos

    This is just perfect for me. Thank you so much for your awesome work.

  • Dennis van Opstal

    Hi Ravi,

    I’m trying to do this tutorial to get some insight in the Rest API, but I got stuck when I tried to implement it in Android.

    When I send a POST to /v1/register I always get the message: “Required field(s) name, email, password is missing or empty”.
    When I use the Chrome Extension from the tutorial(Advanced Rest Cliet) I can add the header “Content-Type: application/x-www-form-urlencoded” and I can register like normal,
    but when I try to add a header to my POST from android it doesn’t seem to work and it just gives the message: “Required field(s) name, email, password is missing or empty” again.

    I have tried it with HttpPost as well as HttpUrlConnection, but it just doesn’t work.

    If anyone could help me that would be great.

    P.S. Excuse me if my english isn’t correct, that’s because I’m actually Dutch

    • Please use Volley library to make the http calls. Use StringRequest to make the request and pass the params in getParams() method.

      http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

      • Dennis van Opstal

        Hi Ravi,
        Thanks for the quick response but I already seem to be stuck.
        I’m trying to make the utils package, but I am not sure where to put it,
        because when I tried making one at the same level as the app package I couldn’t do it.
        Do you by any chance know what I’m doing wrong?

        • You can keep the volley request code in the same activity at least for testing.

      • Dennis van Opstal

        Thanks for that library, it helped a lot!

  • Yash

    Great Tutorial,but 404:not found occurs. Checked the code Twice. Please Help

    • Have you enabled the mod_rewrite module in apache?

      • Yash

        Yeah,its enabled! JSON output says unexpected token <

        • Try to hit the url from a rest api client. You can see the php error and solve it.

          • Yash

            the output is of Rest client. I am using port 34 for apache,let me know if that causes error

          • Port is not a problem. Hit the url from rest client and give me the response.

          • Yash

            Response: Unexpected token <

          • Which rest client you are using. If it is post man, check the response tab view options. Plain, json, etc. Select the plain tab to see the response.

          • Yash

            http://localhost:34/MyTaskManager/v1/index.php when i run this url for checking error(not in rest client) it shows 404:file not found. I am using Advanced Rest Client

          • No, accessing index.php always gives you 404. You have access the final endpoints like /v1/login with exact method POST or GET otherwise you will get 404.

            Give me the screenshot where you are seeing ‘Unexpected token <'

          • Yash

            hv tweeted u the screenshot. check your twitter

          • If you see at the bottom, you can find three tabs. Raw, Parsed, Json. Click on Raw tab to see the response.

            Anyway you are getting 404 not found. Please verify the url again.

          • Yash

            URL is correct

          • is mod rewrite is enabled? Also did you check switch to RAW tab and check the response.

          • Yash

            Found out critical error in code. Now working fine. Sorry,for the hustle. But thank you for the tutorial and ur quick responses.

          • Ruhul Azam

            Hey @disqus_Wa40t1jzIv:disqus i m also getting almost same problem as yours! can u plz tell me how u solved it?

          • Yash

            Hey,Ravi. How can I use this API in android app to perform Login/Authentication with edittexts. Pls reply if possible!

  • Majid Abdul

    Amazing guy out there!
    Best tutorials on Android and well explained.. No words to describe the awesomeness of this website and of course of the creator of this website 😀

    Keep going brother we all love you <3

  • subash khati

    Anyone got this working in slimframework v3?

    • Pradeep Pathak

      yup!

      • subash khati

        If you could share one method using slim3. thanks

      • Brain

        can you share the code in slim framework 3? please i need it for my semester project

  • Sundeep Singh

    Kudos to androidhive and Ravi to u for such a detailed tutorial of restAPI.
    I am beginner in this field and got some issues while running the code.
    when i send the name, email & password through ARC app then i get no response
    the STATUS remains 0.
    i followed the tutorial step by step but still finding this error.
    Please help if u could !

    • First make sure that the url endpoints are working correctly. Use postman to check the urls. If the urls working correctly, give me the code which you used in your app.

      • Sundeep Singh

        Thanks Ravi for the reply.
        I figured out the mistake while going through the GCM_CHAT tutorial of yours.
        I replaced the localhost in the url by the ip address and it worked out fine.
        Thank you such awesome tutorials 🙂

        And one thing i would like to bring u notice that i receive no confirmation mails while trying to download the code from the website.
        Their might be some error, if it will be resolved than it would be of yet again of great usage .
        Thank you.

        • I am glad that you got the clear picture of the tutorial. I have removed the email activation completely, instead I kept the social logins.

  • Yash

    Hey,Ravi. How can I use this API in android app to perform Login/Authentication with edittexts. Pls reply if possible! I am aware of httpUrlconnection just don’t which url to use.

  • Hafiz

    enable mod_rewrite and create .htaccess file inside root directory, works for me. Thanks

  • shiranahmed

    Dear Ravi i am getting 500 Internal Server Error

  • Ruhul Azam

    hi @ravi8x:disqus thanx for this awesome tutorial.
    i have tried as u showed in the testing video, I putted name,email,password but I am getting 400:bad request. And as usual JSON saying : “message”: “Required field(s) name, email, password is missing or empty” . Can u plz tell me how to solve this.?

    • Can you post the screenshot of Postman.

    • Junielo Guardalupe

      I also have this kind of error and I’m using ARC I don’t know how to make it work. Please I need help Mr. @ravi8x:disqus .

      Thank you in advance sir 🙂

  • Sylvain Grognet

    Hi Ravi. Thanks for this tuto! i haven’t found another as well detailed. I’m beginner in this field and i have a problem while running the code. I tried to post a register request and i received a status=200. But i don’t have the response expected and no data has been added in my database. ARC shows me this response (Could you please explain to me what’s wrong?) :

    ( ! ) Warning: require_once(/include/DbHandler.php): failed to open stream: No such file or directory in E:wampwwwtask_managerv1index.php on line 4

    Call Stack

    #TimeMemoryFunctionLocation

    10.0023184728{main}( )..index.php:0

    ( ! ) Fatal error: require_once(): Failed opening required ‘/include/DbHandler.php’ (include_path=’.;C:phppear’) in E:wampwwwtask_managerv1index.php on line 4

    Call Stack

    #TimeMemoryFunctionLocation

    10.0023184728{main}( )..index.php:0

    • Hi Sylvain

      Can you open index.php and add the below line (add __DIR__ . ‘/ in front)

      require_once ‘../include/DbHandler.php’;

      to

      require_once __DIR__ . ‘/../include/DbHandler.php’;

      • Sylvain Grognet

        thank you for responsiveness, I applied your patch and I get the following error:
        Warning: require_once(E:wampwwwtask_managerv1../include/DbHandler.php): failed to open stream: No such file or directory in E:wampwwwtask_managerv1index.php on line 4

        so i rewrote it like that :

        require_once __DIR__ . ‘..includeDbHandler.php’;

        require_once __DIR__ . ‘..includePassHash.php’;

        require __DIR__ . ‘..libsSlimSlim.php’;

        and now i get a 404 status

  • Karthi

    Hai Ravi,

    Am the beginner. . .i need your assistance .

    can u say how to enable the mod_rewrite module in apache

    am using WAMP server

  • Karthi

    i have error when testing with postman extension like below,

    500 Internal Server Error

    Internal Server Error
    The server encountered an internal error or
    misconfiguration and was unable to complete
    your request.
    Please contact the server administrator at
    admin@example.com to inform them of the time this error occurred,
    and the actions you performed just before this error.
    More information about this error may be available
    in the server error log.

    after reading all discussion i guess its because of server cofig error.

    and this error in log as

    C:/wamp/www/gcm_chat/v1/.htaccess: Invalid command ‘RewriteEngine’, perhaps misspelled or defined by a module not included in the server configuration

    Can you help me to short out this,

    am very exciting to work on gcm chat app.hope u rply me soon. . . .

  • bhavesh

    hi ravi,404 error still persists even if i enable mod_rewrite module ! please suggest alternative!

    • Can you give me your postman screenshot.

      • bhavesh

        m using REST API client.
        and the response shows –

        404 Not Found

        Not Found

        The requested URL /task_manager/v1/register was not found on this server.

        Apache/2.4.9 (Win64) PHP/5.5.12 Server at localhost Port 80

        also the url is correct.

        • Can you try this url and let me know

          /task_manager/v1/index.php/register

          /task_manager/v1/index.php

          • Sharel Solís

            I got the same message with both of them
            “404 Page Not Found

            The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.”

          • Diego

            I was the same error, but with /task_manager/v1/index.php/register and the correct method (put, get, post) is ok.

  • Vishal Kumar

    Hi Ravi… everything is working quite well for me… I am not able to test the delete function… also I did not understand … why are using a global $user_id…. Also…. how is the program receiving users/:id… this id passed in the url

    • Normally every user will be identified by the API Key that is passed in the request header. On the server we get the user id using the API Key and store it in $user_id which is a global variable.

      For the delete function to test, you need to make the request to url using DELETE method.

  • karl

    Hi, Awesome tutorial! When I try and post I get 400:Bad Request. The Raw message says:
    {“error”:true,”message”:”Required field(s) name, email, password is missing or empty”}

    I have entered name, email and password. Any ideas what’s wrong?

  • Brain

    hey ravi i just want to ask, how can i make url like this work in slim http://192.163.0.13/event/event.php?page=1

    I need to give limit so each page only give 5 item for example. like pagination case
    so i can use like in your tutorial http://www.androidhive.info/2015/05/android-swipe-down-to-refresh-listview-tutorial/

  • Dušan Dimitrijević

    Hello Ravi,

    Can you help me with error message i’m getting when i try to send post method for tasks. In my case i have groups. This error message i’m getting:

    {
    “error”: true
    “message”: “Required field(s) task is missing or empty”
    }

    And i have done everything like you.

    • Braja Pal

      if everything is ok than you might haven’t given headers like Authorization key(api key) and Content-Type .i had also similar issues . i fix this way 🙂

  • Trupti

    Hello Ravi,
    Firstly thanks for this nice tutorial. I am new to PHP. I am using Eclipse & created a project in www folder workspace. When i try to execute index.php – it give 404 error. I can’t even see v1 folder in my folder path thru http://localhost:81/tridrops/tridrops in browser. I tried removing .htaccess from v1 folder, & the folder is accessible & seen in browser too. But when I execute – http://localhost:81/tridrops/tridrops/ver/ thru browser or Eclipse inbuilt – it gives me 404 error.

    404 Page Not Found

    The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.

    Visit the Home Page

    Sometimes, i get this error (I dont remember when exactly as lots of RnD :

    500 error –
    Internal Server Error

    The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator at admin@example.com to inform them of the time this error occurred, and the actions you performed just before this error.

    More information about this error may be available in the server error log.

    Apache/2.4.9 (Win64) PHP/5.5.12 Server at localhost Port 81
    Can you help me know what is the error and why the .htaccess file is causing problems. I am stuck badly and couldn”t find any resource since last 2 days.

    It would be really nice, if you can help me and assist me soon.

    Thanks

  • Tamir Zimerman

    Hi Ravi,
    Maybe I wrong but not the whole point of using salt for hashing is to save the salt for later check of the password? when you check the password you create a new salt so it’s never gonna equal a random salt from before?

  • Chauhan Ajay

    Hello Ravi, First of all thnxx for this tutorials,
    can you tell me how can i make rest api as your code is given above, but without using third part library (slim) and .htaccess file also i want login.php and register.php saperate file rather than having single file like index.php.
    and i want to use .php extension in POST MAN to run the script…

  • Thato Rammoko

    Hello Ravi I seem to be getting this error on Post man {

    “error”: true,

    “message”: “Email address is not valid”

    }

  • Braja Pal

    Hello Ravi is there any other technique consuming in php rather than cURL ..

  • Trupti

    Hi Ravi,

    Thanks for this nice tutorial. I have created my project using Eclipse under www folder. Currently, I have just added 2 API methods – post & get. I cannot access any of them thru Ad Rest Clinet. I keep on getting 404 error.

    I have shared code over here – http://stackoverflow.com/questions/36107839/wamp-server-cannot-execute-any-php-rest-api

    /ver – version folder
    Just running “http://localhost:81/tridrops/tridrops/ver” on browser also gives 404 error.

    Any idea why is this & how to resolve it.

    Your help is highly appreciated.

    Thanks

  • Isabelle

    Hi Ravi. Thank you for this really well-explained tutorial. I did all the steps and unfortunatelly, I’m facing the 404 error when trying to call the api. The mod rewrite module is enabled, htaccess is good and I get a 404 message as response when calling my localhost address: (http://api/register).
    Your help would be highly appreciated.

    • Isabelle

      I will dig into the Slim routes ^^

      • Alex

        have you fixed this issue?

        • Isabelle

          No, then I switched to Firebase 😉

  • Dušan Dimitrijević

    Hello everyone. Can anyone tell me how could i update user details?

  • Faruqi Muhammad

    HI Ravi, i’ve problem about 400 Bad Request. Error from function verifyRequiredParams i think. Can you help me how to fix that? Thanks.

  • nikhil reddy

    Hi Ravi Firstly Thank you For This Article

    I am facing one Issue while creating a new task http://localhost/task_manager/v1/tasks
    I am getting response as {“error”:true,”message”:”Api key is misssing”}

    Please Help Me Out

    Regards
    Nikhil

    • You need to pass API Key in request headers. Check volley request getHeaders method.

      • nikhil reddy

        Thank you now It’s working for me

        • giba11

          check Blackcode answer, works like a charm

          Hi huron123,

          I’m using Advanced Rest client and I was getting “Api key is missing” too.

          I guess your configuration should be like that:
          —————————————————————
          URL:
          http://localhost:81/task_manager/v1/tasks

          RAW HEADERS:

          Content-Type: application/x-www-form-urlencoded
          Authorization: 1234567890 (string(9) “localhost”
          [“content-type”]=>string(33) “application/x-www-form-urlencoded”
          [“authorization”]=>string(32) “1234567890” (string(2) “11”
          }

          Try it and tell me if it has worked

          Regards 😉

  • Rajani

    Hi Ravi thank you very much for this tutorial. Its helped me a lot. And everything is working fine.

    Can you provide me code for logout.

    Thank you,
    Rajani.

    • There won’t be any logout in rest api. If you want to do changes when user logs out, create an endpoint for logout and write your php logic there.

  • huron123

    Hi,

    When i try http://localhost:81/task_manager/v1/tasks i get the following message

    {“error”:true,”message”:”Api key is missing”}

    Why? Register and Login works fine but it seems like i’m getting empty header in the server when i try the other actions which requieres the apikey. I’m using Advanced Rest Client Application and i’m passing in the header the APIKey

    • BlackCode

      Hi huron123,

      I’m using Advanced Rest client and I was getting “Api key is missing” too.

      I guess your configuration should be like that:
      —————————————————————
      URL:
      http://localhost:81/task_manager/v1/tasks

      RAW HEADERS:

      Content-Type: application/x-www-form-urlencoded
      Authorization: 1234567890 (string(9) “localhost”
      [“content-type”]=>string(33) “application/x-www-form-urlencoded”
      [“authorization”]=>string(32) “1234567890” (string(2) “11”
      }

      Try it and tell me if it has worked

      Regards 😉

      BlackCode

      • Greeny

        Thanks for your precious help Blackcode !!!!!!! 🙂

      • Ravi Basil

        not working friend

  • nagina asghar

    hi,
    Ravi sir can u help me to resolve this ?? as i am not able to resolve it.

    v1/index.php

    404 Page Not Found

    The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.

    Visit the Home Page

  • Pance Satria

    Hi, can yout help me. When i register and input email like this “example@yahoo.com”.
    The output says the email address is not valid. Thanks before

  • Alex

    Hi Ravi. I am getting a 404 error.. Please help.. thank you..
    I tried the following urls

    http://localhost/task_manager/v1/
    http://localhost/task_manager/v1/index.php
    http://localhost/task_manager/v1/register

  • alfredo caldera

    hi
    i had the 500 internal server error => problem resolved, i didnt have the Slim library in the right path you can get a lot of information in the apache LOG file

    i also had the 404 error => like Ravi Tamada said in a post try using http://localhost/task_manager/v1/index.php/register, http://localhost/task_manager/v1/index.php/login, etc. This problem is a missconfiguration in your apache files (i dont really remember now where sorry)

    The no api key problem, i did some tests and found out that my headers are sent as “authorization” but in the index.php file the validation is against the field “Authorization”, that capital ‘A’ is the problem in my case. Take a look on how your apache is using that field..

    i wasn’t using WAMP, i installed everything on a Linux Mint using the repositories…

    I hope this could help you

  • మోదుపల్లి శేషాద్రి నాయుడు

    Hi Ravi..

    first i thank you give great rest API code.
    i follow all step call REST API in rest console
    I get 404 found error

    i enable rewrite_module
    but still i get same error
    give me response ASAP
    The requested URL /task_manager/v1/register was not found on this server.
    like this

  • kelomaniack

    Hey Ravi,

    Great article man.
    It helped me alot with some stuff i needed to do (and understand of course).

    Gongrats! Keep up the good work!

    Cheers

  • An

    Hello Ravi,
    Thanks for your article.
    Could you help me to make clear about the using of api_key in app (or web). As I understand, after we create a user, we have one api_key (each user will have a different api_key?). And we we make a request to any api, we must pass api_key into request header, so how can we do that? Do we get api_key after login and pass it to request header?
    Thanks,
    An

    • An

      I mean: how to store api_key in client side, example I use ajax to call api not Postman?

  • Milan Gajera

    Hi Ravi,
    First of all thanx for great tutorial. When i want to add the tasks using my android application.
    How can i set the logged user api_key from header so that i performed a operations like add tasks, view tasks etc.

    There are different api_key for different user? How can i maintain using android application code?

    • Ziigic

      using request header on vollery library

      • Milan Gajera

        Thank Q @ Ziigic

      • Joeyz Lola

        Have u done with android application? If yes, can u share ur complete code with me? i’ve no problem with register and login. but to create task i still fail to create headers to authenticate. ^^ my emel : himynameisfaizul@gmail.com

  • Milan Gajera

    It is request to you. You need to also post the android code to perform all above tasks.

  • daniel

    Awesome tutorial Ravi thank you very much!!
    I had problems receiving the 404 error too.
    I was getting error 400 because in index.php this line
    $app->run();
    was not at the end of the file, just somewhere in the middle (because i just copied the code following the tutorial one block after another without paying much attention).
    So if anyone has the 404 response just chek as well that this line of code is where it needs to be!

    • Maki

      So you mean $app->run(); should be at the bottom part?

      run();
      ?>

      • Tanmay Jha

        @Maki Yeah bro.!
        @daniel Thanks alot mate! 😀

    • Prajwal Sandeep

      Daniel superb catch, beginners like me need ppl like u, worked like a charm, thanks buddy 🙂

  • Maki

    Hi Ravi, is the android part of this not out yet? If yes pls share the link pls. =) Thanks. Your tutorials are great. It helps me in my projects.

  • Android_learner

    Hello,
    I am having this problem while testing the API.
    http://i.picpar.com/VdPb.png
    Non-Space characters found without seeing a doctype first..
    Can anyone help me?
    Also the same problem occurred when i tried Android Building Realtime Chat App using GCM, PHP & MySQL
    (http://www.androidhive.info/2016/02/android-push-notifications-using-gcm-php-mysql-realtime-chat-app-part-1/)

  • Milan Gajera

    Hey ravi great tutorial but not working with volley library. your login and registration tutorial working with volley library. when i tried to login so my login url is like http://ip_addr/root_directory/v1/login using volley not working but using http method it’s work.

  • Milan Gajera

    if above tutorial working with volley then please, send me a sample on my email.if it is possible.

    • Maki

      yah, pls send us the android part thanks

  • Ashutosh Kumar Mantoo

    Hi, Please any one can help me , i am getting the error like “404 Page not found “. I have already checked out the Apache Rewrite_mode module it was enabled.

    • Basheer Ritz

      what was the url u given while posting

  • Ziigic

    Hi Ravi, great tutorial. Can you help me ?
    http://localhost/task_manager/v1/tasks
    this line work on my localhost, but not work on my share hosting.
    It’s return 500: Internal Server Error.

    I’m using echo script to check which error line.
    $tasks = $stmt->get_result();
    not work on my share hosting. Something must be enabled first or something else ? Please help me.

    • Ziigic

      I got this error_log
      PHP Fatal error: Call to undefined method mysqli_stmt::get_result()
      I’m already using php 5.6, with mysqlnd, mysqli enabled.

      how to solve this ?

  • Sachin Chaudhari

    Nice tutorial,
    please help me?
    I want to Upload image.

    This is my code for upload image,

    $photoid = $app->request->post(‘photoid’);

    $suffix = uniqid();

    //assigning an image name..

    $path1 = dirname(__DIR__);

    $image_name = $path1.”/task_manager/”.” img”. $suffix . “_” . date(“Y-m-d-H-m-s”) . “.jpg”;

    $path = “task_manager/”.”img”.$suffix.”_”.date(“Y-m-d-H-m-s”).”.jpg”;

    move_uploaded_file($photoid,$path);

    but its not working, Please share code for upload image.

  • upasara wulung

    $app = SlimSlim::getInstance(); not working in Slim 3. How to handle this?

    • Dedi Ananto

      i have same issue when using slim 3. @ravi8x:disqus : can you make tutorial using slim 3 for this case

  • Riccardo Bella

    Hi! I’m trying to upload files, is this function:
    verifyRequiredParams
    compatible with fiel upload or i have to another one?
    Thanks!

  • Mila Zogovish

    Hi Ravi,
    First of all thank you for your tuto, it’s very helpful. 🙂
    I added other fields in the database (phone number, nickname, etc… for example). When executing the “register” php in the chrome extension, I don’t get any data for these new fields…

    Thanks a lot for your appreciated help !

  • snehalp77

    Hi Ravi,

    fantastic article, was wondering is there anyway to avoid writing code for each table like what is being done here https://github.com/mevdschee/php-crud-api ?

    Thanks

    • Yes, this is just getting started article. You can definitely go for better alternatives to make the things simpler.

  • Alan

    Hi Ravi, Best tutorial i have read in a long time well done. I did the Authorization -> authorization to get call working in Advanced Rest Client then i ran into issue with PHP Clients making it uppercase automatically and ended up making a unique verb “authorization1” by changing the two “Authorization” references in index.php and just sednign the new verb in header similar to old one. On another issue The returned data is not pure JSON. Can you tell me if i need to adjust the server side to send in JSON format or can i do something clever with the response as is. appreciated thanks Amcell

    • Alan

      actually i just replaced / echoRespnse(200, $response); with echo json_encode($response); and i bypassed the json syntax errror unexpected char – so all good. thanks. onto uploaded and retrieving images now….

      • Alan

        still one issue Ravi. My GetTask Response from PHP Ajax Client contains DBHandler.php within the response string complicating my parse. Is this normal? anyway to remove the reference. I could not see any way to adjust teh return in DBHandler.php. thanks Alan

        • Alan

          Sorry for being such a noob Guys but, Can someone explain to me why the DBHandler.php filename is being returned in the Response from index.php is this valid JSON? Do i need ot parse to remove the DBHandler.php text. Thanks in advance

  • Harish

    HI Ravi,

    Thank you very much for the tutorial. I am beginner for webservices. I have copied the same code but while testing on poastman client and Advanced rest client I am getting error like this

    ( ! ) Warning: require(.././libs/Slim/Slim.php): failed to open stream: No such file or directory in C:wamp64wwwtask_managerv1index.php on line
    5

    please can anyone tell what i did mistake..??? Thanks in advance

    • Alan

      If I assume you loaded the slim library correctly . I downloaded slim lib and unzipped to libs directory. The Libs Directory is at same level as v1 directory. My require is same as yours in index.php and mine is working, must be something simple 🙂

  • Jamie Hsieh

    Hello Ravi,

    First,thanks a lot this Tutorial,it helps me in many aspects.

    And I encounter a problem that 404 error.
    I check error log in apache2,that it say File does not exist: /var/www/task_manager/v1/register
    But I have copy the register code in my index.php before app run.
    Wish you can help me.
    Best regards.

    • Jamie Hsieh

      PS.I use docker for this api,and apache2.conf doesn’t contain the

      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted

      And I change them in root.

  • Allen chang

    Hi, Ravi
    I like this tutorial.Could you provide a exmaple of using php upload files with header Authorization,please.thanks

  • Saeed

    Hi Ravi, Thanks for your great tutorial, could you please say where do you set $headers[‘Authorization’] in this example , i can’t find that.

    • Mohamed

      He doesn’t the $headers = apache_request_headers(); line in the top returns array of all the headers sent by the user for example the ip address and any custom headers included, Including ofc the api key, So at the android part of the code you must include the api key in the header

  • Dan

    About the error 404 on an ubuntu 14.04 machine,

    The apache logs are pretty useful. I had to edit DbConnect.php and DbHandler.php in the “include_once dirname(__FILE__) . ‘./Config.php’;” where you remove the .(dot) before the Config.php for DbConnect.php and before the DbConnect.php in the DbHandler.php file.

    And only worked with http://localhost/task_manager/v1/index.php/register for me.

  • Abhishek shrivastava

    hello Ravi,
    I had uploaded the file on server but i am getting response 201-Oops error while registering.
    Actually the createUser function is not working in DBHandler. I dont know much about php so can you please tell me how bind_param is working because when i am passing predefined values it goes to database and when taking app->post its not working.

    • anonymous

      I think the biggest issue is him not actually setting anything into the response..

  • Csaba

    Thanks Ravi, I just finished my first REST API by your useful article and am very happy to be learned so much. 🙂

    • You are welcome Csaba. Happy Coding 🙂

      • Hemant Verma

        hlo ravi sir…i want help in your retrofit lib example…i just want to go on next page by clicking on any row element from recycle list view

  • chimuka moonde

    after a lot of debugging,reviewing and comparison of the source code with my own code,i have finally completed the REST API ,thanks a million Ravi Tamada,its been really amazing learning from you,i must say i find implementing REST API using Slim framework is much more challenging than using node.js and express.js to implement a REST API

  • Chris K

    Hi, great tutorial. Actually it is one of the best REST API with Slim out there for beginners but still there are some mistakes. Maybe on purpose as an exercise for us or maybe because of different systems,commands and so on.

    I spot these:
    1. include_once dirname(__FILE__) . ‘./Config.php’; //this gives me an error. I replaced with include_once dirname(__FILE__) . ‘/Config.php’; (no dot) and it works. Do the same for other require commands. Also check the path for slim.php, mine for that is: require ‘../libs/Slim-2.x/Slim/Slim.php’;

    2. I was getting Api key is missing when I tried to test with authorization header and its value. After debugging I found out that on the checking key code it should be ‘authorization’ and not ‘Authorization’. Like that:

    // Verifying Authorization Header
    if (isset($headers[‘authorization’])) {
    $db = new DbHandler();

    // get the api key
    $api_key = $headers[‘authorization’];

    I know many people are getting frustrated cause of errors D:
    Thanks! 😀

    • Tanmay Jha

      Thanks man! I wouldn’t have cracked that authorization error for long.

    • Meisam

      thanks a lot 😀

    • Ken Choong

      thanks bro,this is work..

  • anonymous

    Hi there, nice tutorial. I am slightly confused as to how you send back the error in createUser (DBhandler class). You return USER_CREATED, USER_EXISTS, etc But how do you bind it to the $response ? I see you return it from an if statement, and exit the method with the return of the $response. But would $response not be empty? You initialized it but I see no setting/pushing of anything into the array

  • anonymous

    Hi, nice tutorial. Where do you put the JSON_DECODE to process data from say an app ?

  • toan nguyen duc

    I get error with code 400 bad request when i call api register:
    {
    “error”: true,
    “message”: “Required field(s) name, email, password is missing or empty”
    }
    Who can help me fix it?
    Thanks!

  • hamid

    hi ravi thank for your wondeful site ; i have learned to much from you ; i have a question . how can i use the url in the browser address for for example http://localhost/task_manager/v1/tasks?authorization=xxxx ;
    but it still says that api key is missing ..

    • You Hamid,

      You can use this in browser. The api key has to be header filed which can’t be done is browser directly. So use chrome postman extension to send the request as explained in the article “Testing the API”

      • hamid

        thanks bro

  • hamid

    hi ravi i want to insert an array list to mysl instead of one single row . can you give me key how can i do it ?

    • Sachin Chaudhari

      Use
      foreach(){
      //write Sql query here
      }

  • Ilson Gates

    http://localhost/task_manager/v1/register

    {
    “error”: true
    “message”: “Api key is misssing”
    }

    Please help me

    • Ashok

      for me too same issue please help me out !!!!!!!!!!!!

      • You need to pass the API key in headers. Check the demo video for reference.

        • anon

          i have a problem

          Fatal error: Call to undefined function apache_request_headers() in

          /API/API/php/task_manager/v1/index.php on line

          20

          • anon

            i find

            if( !function_exists(‘apache_request_headers’) ) {

            function apache_request_headers() {

            $arh = array();

            $rx_http = ‘/AHTTP_/’;

            foreach($_SERVER as $key => $val) {

            if( preg_match($rx_http, $key) ) {

            $arh_key = preg_replace($rx_http, ”, $key);

            $rx_matches = array();

            // do some nasty string manipulations to restore the original letter case

            // this should work in most cases

            $rx_matches = explode(‘_’, strtolower($arh_key));

            if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {

            foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);

            $arh_key = implode(‘-‘, $rx_matches);

            }

            $arh[$arh_key] = $val;

            }

            }

            if(isset($_SERVER[‘CONTENT_TYPE’])) $arh[‘Content-Type’] = $_SERVER[‘CONTENT_TYPE’];

            if(isset($_SERVER[‘CONTENT_LENGTH’])) $arh[‘Content-Length’] = $_SERVER[‘CONTENT_LENGTH’];

            return( $arh );

            }

            }

            $headers = apache_request_headers();

  • Larcenciels

    hi ravi, just one my question, how to reset password if user forgot their password ?

    • You need to integrate email service which sends password reset email.

      • Larcenciels

        I know how to build email service, but hoe about query and the php code, i familiar with iava but not in php, can you show me an example ?

  • Joeyz Lola

    Hi ravi. Thanx for this cool tutorial. I believe there is another part on android side? I’ve already implement this tutorial with volley and i’ve no problem when register and login. But on sending task, it’s required u to authenticate with api key right? And i’ve created volley string request and add this method.

    @Override
    public Map getHeaders() throws AuthFailureError {
    HashMap headers = new HashMap();
    headers.put(“Authorization”, apikey);

    return headers;
    }

    Am i doing this wrong bcoz it gave me 400 error which means “Api Key is Missing”. I assume that apikey value is empty but i try to change it like, headers.put(“Authorization”, eaec962fcc26cb9fbce351daefdd6784); and it still gave me the same error. Can u help me on this?

    • Dump the request on php side and see what you are getting in request header.

      • Andrii

        Best tutorial. Thanks you Ravi!
        i also has this mistakes. i solve it, change “Authorization” to “authorization”
        (in index.php and in request header). It will be solve you 400 error.

  • Gsp Ivan

    Hello Ravi am trying to test the API using postman as u sugeested but i keeep on getting this response , what could be missing

    404 Page Not Found
    The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.

    Visit the Home Page

    Any help wil be highly appreciated

  • Junielo Guardalupe

    Hi sir @ravi8x:disqus I am now using the Postman and I can do a add user and add task but the problem is I can’t seem to update the task. It says:

    {
    “error”: true,
    “message”: “Required field(s) task, status is missing or empty”
    }

    although I supplied both.

    If anyone has a solution please share.. thank you!!!
    And I’m also new to php..

    • You are not sending the required parameters task and status. Pls post the screenshot of your postman request.

      • Junielo Guardalupe

        Thank you for the reply sir but actually it is really my fault that I put the parameters to the header instead in the body. I followed your instructional video and it worked perfectly fine.

        Anyway thank you for your tutorials sir it helped me a lot with my work.

      • Junielo Guardalupe

        Thank you for your response sir but it is really my fault that I enter the parameters to the Headers section instead in the Body and by following your instructional video, it is working perfectly fine now.

        Anyway thank you for tutorials sir it helped me a lot with my work and I know the others too as well.

  • Ram D

    hi Ravi Tamada

    when i am using this url: http://localhost:8080/task_manager/v1/register
    i am getting 500 error
    I could not under stand where to place the register user login codes pls hlp me…………… thanks in adavnce

    • Check the php error log or php error reporting.

      • Ram D

        I am getting $app undefined variable

  • waxi

    Warning: require(.././libs/Slim/Slim.php): failed to open stream: No such file or directory in C:xampphtdocstask_managerv1index.php on line 5

    Fatal error: require(): Failed opening required ‘.././libs/Slim/Slim.php’ (include_path=’.;C:xamppphpPEAR’) in C:xampphtdocstask_managerv1index.php on line 5

    how to solve this ??
    i think its library problem becouse there is no slim.php file in that path … :/

    • Hadi

      I am getting similar issue. Did you resolve it, How?

      Thanks

      • Aman Jain

        Shit Post wasted my time, No Slim.php is available in Slim framework

  • Finn Deagle

    hey, can we use it in android aplication??

  • Maciej Stosio

    Hi, is it bad practice to connect to the database in constructor instead of creating another class?

    • Moving the connection to a single class makes it easier to optimize and organize.

      • Maciej Stosio

        Ah, okay.
        But i have one more question.
        I’ve fallowed this tutorial, but i’ve got another issue. I’m getting error like this:
        “XMLHttpRequest cannot load http://localhost/v1/api/user. Response for preflight has invalid HTTP status code 404″
        I know that I’m using cross domain request, I’ve changed http header in .htaccess file, but it doesn’t work with authorization. I know that using this header, I’m doing more complicated request, something called “preflight”.
        I fixed this creating 200 response for OPTIONS request like this:

        $app->options(‘/user’, function(){
        echoRespnse(200, “true”);
        });

        But it doesn’t seem to be nice solutions. Can you help me?
        Thanks,
        Maciej

  • Noeurng Ouch

    I’ve followed the direction and everything is exactly the same, but I have an error of 500: Internal Server Error. Even thought I download your source code and test it, there is the same error appear.

    https://uploads.disquscdn.com/images/722952ca44ee3b88cc775e55b5e507b42e3c45a405d1706e2bffbd9f9e51f928.jpg https://uploads.disquscdn.com/images/e66082ab59325e8cb71bb8928f03361fc88bbae1210dfa56a48a3c20f9226ac9.jpg

  • Narayana

    Hi Ravi,
    Its a great tutorial but i am getting silly issue ,I am always getting error response like ” “message”: “Required field(s) name, email, password is missing or empty”” even after placed required fields .Please find the my attachments and check your project once .Please help me.

  • Chandrakant

    Hi Ravi, I’m getting error, email address is not valid.
    Ex. Ravi@gmail.com

  • Arjun Singh Kushwah

    https://uploads.disquscdn.com/images/e452c90d8d1bce1f319ece1c5605895aae08a7927382fa508e7e3702c5016400.png Hi Ravi,
    I am very new to php rest api. I followed the same steps even tried the downloaded code but i am facing 404 Page not found error for every request.

    One more thing can you help with cross-origin request error, what modification needed to be made in .htaccess file and index.php

    • Hi Arjun

      I can see two mistakes here.

      1. You are accessing a wrong url. Check login spelling. It should be /login not /lgoin

      2. I assume, login url should be accessed in POST method not GET. When you access the url via browser it makes GET request. That’s why you are getting 404 error. Use postman and send a post request to same url. Check the video provided in the article.

      • Arjun Singh Kushwah

        Hi Ravi, thankx got the point When i access the url via browser it makes GET request. That’s why i was getting 404 error.

        Can you help me with CORS issue?

  • Vinod Dirishala

    Ravi i am getting internal server error 500 when i am trying to post data using the link http://localhost/task_manager/v1/register .

    • samir

      same here

  • Vinod Dirishala

    Here is apache error log message

    [Sun Dec 18 11:57:47.859689 2016] [core:alert] [pid 7620:tid 1108] [client ::1:56720] C:/wamp/www/task_manager/v1/.htaccess: Invalid command ‘RewriteEngine’, perhaps misspelled or defined by a module not included in the server configuration

  • Vinod Dirishala

    after i resolved that rewrite engine error …i am getting slim application error. below is the screenshot of that
    https://uploads.disquscdn.com/images/75850770670cfa94f8590d0374852efb50e4eac7d5d797ad27eff1d2a72df9f2.png

  • samir

    https://uploads.disquscdn.com/images/252ec63d00a534b4ef3001d1c1c462aa84b34ee77f9f345ef6a36e57be3a4819.jpg Hello ravi i follow your tutorial and make all settings done but problem is i’m getting 500 error can you explain me what it’s happening and why.

    i am a android developer and have basic knowledge of php.

    Completer error below

    Internal Server Error

    The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator, admin@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.

    More information about this error may be available in the server error log.

  • I am glad this helped you a lot Skillz 🙂

    • rehan

      Can you please update this tutorial with the Slim 3? This Api is not working with the Slim 3 Framework. Its working only with Slim 2

  • Tung Pv

    Hi Ravi Tamada, I have issue with No ‘Access-Control-Allow-Origin’ header, so please help me how to resovle thanks

  • Aman Jain

    Shit Post wasted my time, No Slim.php is available in Slim framework.

    • It’s not the post. It’s the ability you have to understand the article. Try figuring out the problem.

  • Ray Pearce

    Great guide but I continue to get a page not found error
    http://onguardapp.com.au/v1/login

    • This link should be accessed by POST method not in browser. Use Postman to send request as shown in the video in the article.

  • Yigal

    Hi Ravi,
    One of the best guides I’ve ever read! Thank you!

    According to your PHP code, Can you please explain what is the best way to log the mysql error messages inside your DbHandler.php code (using mysqli_error or any other way).
    I want to add those errors to the response JSON.

    TNX,
    Yigal.

  • Yigal

    Another thing…

    I saw that the connections are not being closed (Only statements, using the $stmt->close();)
    Don’t we need to close the connections as well? Is it needed in Prepared statements?

    TNX,
    Yigal.

    • Not needed. They will be closed automatically.

  • druid

    For all of you having problems with 404 file not found error message, there is a preaction that has to be done (mentioned in next article though) in order to be able to test it:
    In /etc/apache2 find file apache2.conf and make this part look like this:

    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted

    It allows overriding and will not function without this change.

    Regards

  • Juanjo Luna

    https://uploads.disquscdn.com/images/7a33d7feb18fb4f2dfb5c92e525a298dc6f24a93c9fc8840b1c9470ca0ded93c.png Hi. First of all. Thank you for your work. It´s wonderful.

    I´ve got a problem.

    when I test the REST i obtein aa 400 error

    but i think the parameter it´s ok.

    can you help me?

    Thank´s a lot

    JUANJO

  • Ken Choong

    So in android,is it post the request to abc.com/v1/tasks for the response?
    For example,I make a function of update activity,then I just post the request to http://localhost/task_manager/v1/tasks/:id using Volley and get the JSON result??Am I right??

    • Yes, but prefer using PUT request when you are updating.

      • Ken Choong

        so is Request.Method.Put in the volley for UPDATE single task right??

  • Jacek Budzynski

    I’ve just started following this tutorial and tried to download the code but the button on top of the page doesn’t seem to work. Could someone provide me with the files from there please?

    • I fixed the server problems. You can download now.

      • Jacek Budzynski

        Awesome! Thank you so much for the tutorial and files. Just starting work on my graded unit project for college and this should be really helpful.

  • Joel Kuiper

    Thanks for the tutorial!

  • ROHIT CHAKRABORTY

    followed the post and everything worked out brilliantly as expected !!
    But now if I want to connect this database to my android app for login and sign up purpose ?
    any tutorial for that?

      • ROHIT CHAKRABORTY

        Thanks for your quick response !! I have hosted your project task_manager online using the digitalocean droplet as per your third article .Works great , i used Postman to create registration online and all worked out great.
        also, I saw this project too .(http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/)

        so , what changes should be done in the android app of this , to continue using task_manager isnted of android_login_api ? on top of my head one is AppConfig.java , where i replace my ip.login and registration api are handled in index.php itself , so any changes needed there in the db ?

      • ROHIT CHAKRABORTY

        So , i went ahead , changed config.java according to the link you posted , also previously hosted the task_manager using digital ocean. So with then change in endpoint api url , when i signup data is getting posted in my data base . But cant login after that with the registered data. says “json error:no uid” .. i suspect theapikey needed for login for user , but where to add it in the android app

  • Davide Binetti

    Same here as others! Keep having problem with validateEmail function. Response always says “Email address is not valid”!
    Try dumping the var get me NULL! Any ideas?

  • Whatever

    Hi,
    Thanks a TON for this very very useful tutorial!
    I’m building an Hybrid mobile app using Ionic 2 framework and was looking for a way to use my existing user database from my website for authenticating purpose in my upcoming android app.
    After successfully testing your api, I think I can finally use my website user accounts in my app.

    However, I also found many developers using JSON Web Tokens (JWT) for user authentication in their app.
    So my question is:

    1. What is the difference between JWT based method and this one?
    2. Which method is better and why?
    3. Can we somehow implement JWT in your api?

    • JWT is just token based authentication. Check whether Slim is providing JWT based authentication or not. If you are seriously considering PHP as backend, consider using Laravel Framework as it much popular.

      • Whatever

        Thanks for the reply.
        I’ll definitely look into that.

        Another thing I want to know is, if I implement this code in my mobile app, how do I logout a user?
        and
        How can I add my own API calls (“/call” for example)?
        is there any guide to follow?

  • Shiroyasha

    Is there alternative way to use get_result()? is i use on web hosting, i got an error: Fatal error: Call to undefined function mysqli_stmt_get_result()

  • Sudip Kumar

    Hi Ravi,

    I Got this error on any api function calling. Please help me out.

    Here is the screenshot

    https://uploads.disquscdn.com/images/f698c32ff69c9ae45ef0b04561045760520a6192c0a354b4185f0f1e22860d2a.jpg

    • You are sending the params in Header section. Instead mention them in Body tab.

  • Mahendra Rajeshirke

    awesome dude

  • Fidelis

    Hi Ravi, I copy your project but still have an error “api key is missing”. I’m sure it’s all correct such as in your video. Why?

  • Hosein Mirian

    It was great, but for intermediate Android programmer like me, it was not satisfying! because someone like me likes to see how we can implement something from zero to 100. I do not want you to present everything but I ask you kindly to prepare a tutorial to teach how we can connect Android program to Rest API and interact with each other. In addition, if you mix it with Volly Library or other high-tech library, it would be great, viable and practical.

    • When you are an intermediate Android programmer, you can explore more and find the solution easily.

      • Hosein Mirian

        Then I am beginner I suppose !!!

      • Hosein Mirian

        Ok, You are right. I should make more attempt to find out the solution. I m sure I can.

  • Hosein Mirian

    It gives me an Error. I use the latest Wampserver. Do you think the problem is related to my Wamp verison or any other reason?I just did the Register command. https://uploads.disquscdn.com/images/1d1b3e72922f15161da57ca14e823f29c055a56cada8d08721da5ab11f281517.png

  • Harsh Mittal

    Hello Ravi,
    I found it very good stuff.
    when i was trying to register it keep return this on godaddy server:

    Fatal error: Call to a member function bind_param() on a non-object in
    /home/infinitumadmin/public_html/App/include/DbHandler.php on line
    103

    But i want to make a rest api for android and login registration for app.
    Is it slim good for that or should i use any other ?

    One more question:
    I want to use this on godaddy server also. how to change index.php on that.

  • Narayana

    Hi Ravi,
    Stopped working your API,All POST methods are not working .Please look into this and update .

  • Narayana Rao

    Hi Ravi,
    Stopped working your API,All POST methods are not working .Please look into this and update .

  • Mahendra Rajeshirke

    I Have used html form and write following code to register user, it works

    var baseURL1 = “http://localhost/rnd/php_slim/task_manager/v1/register”;
    function RegisterUser() {

    $(‘.ui-loader’).show();
    var Name = $(‘#name’).val();
    var Email = $(‘#email’).val();
    var Password1 = $(‘#password’).val();
    var data= {
    “name”:Name,
    “email”:Email,
    “password” : Password1,
    }
    $.ajax({
    type: “post”,
    url: baseURL1,
    crossDomain: true,
    dataType: “json”,
    data:data,
    contentType: ‘application/x-www-form-urlencoded’,
    cache:false,
    timeout:20000,
    async:false,
    success: function(data, textStatus, jqXHR){
    $(‘.ui-loader’).show();

    $(‘.note’).empty().show().html(‘Registered User Successfully’);
    $(‘.ui-loader’).hide();
    },
    error: function(jqXHR, textStatus, errorThrown){

    },
    failure: function (response) {
    //$(‘.ui-loader’).hide();
    $(‘.note’).empty().show().html(‘Submission failed due to server on internet connection. Please try again’);

    }
    });
    }

  • caio martins

    Very good your tutorial, did and is running perfect.
    I would like to consume the data by Android, have any material available?

  • Sangif

    Fantastic tutorial!!thank you very much for sharing!!!Could you shed a some more light on this line of code:
    // now assign the task to user
    $new_task_id = $this->conn->insert_id;
    I would like some clarification on how that line is doing its work.
    Also this line;
    global $user_id;
    How is the variable $user_id automatically passed the value when there is no step where you assigned the value? Your help will be extremely valuable.

    • Sangif

      Forgive my ignorance…i re-read the code and realised where $user_id was assigned. For anyone who was questioning themselves about insert_id, it returns the auto generated id used in the latest query. Thanks again for the tutorial. It helped me a whole lot! Loyal follower here.

  • Tanvir Rahman

    Hello Ravi,
    Can you please tell me how can I get non English font via slim with GET method, I try your code, everything is working but nonenglish font is show ???????, Please help me

  • Igor

    hey Ravi I copied your project and followed all the steps but when i try to access the url it gives 404 error

    • Firdous Farooq Bhat

      use chrome browser extension like postman

  • Mahendra Rajeshirke

    Hello Mr. Ravi,

    The framework i have used and it was awesome but when i tried to create task on my localhost from the server where i set up API. It’s giving error — execute() failed: Column ‘user_id’ cannot be null. I have also posted the question here http://stackoverflow.com/questions/43230779/mysql-external-php-api-column-issue-failed-to-execute

    Can u please look into.. I tried alot.. API and form working fine on same server but not with cross domain…

  • pranav kashyap

    Hey Ravi ,
    wonderful sharing you are doing!!

    I require some help with slim library ,, when i tried with your code. Using Slim V 3 , it gives me below error when tried first response http://localhost/task_manager/v1/register

    Fatal error: Trait ‘SlimMiddlewareAwareTrait’ not found in E:Xampphtdocstask_managerlibsSlimApp.php on line 48

    what is required from my side to solve this MiddlewareAwareTrait ?

    Your help will be much welcomed and appreciated.

    Thanks
    Pranav

  • Ufere Peace

    Thanks so much for this tutorial, quite detailed. But i keep getting 500 Internal Server Error on Chrome ARC. And i dont get any error logged on my phperror.log. I use MAMP and PHP 7. Is there any help you can give. Thanks so much for making the concept of REST easier to grasp

    The message on ARC is thus:

    Slim Application ErrorThe application could not run because of the following error:DetailsType: ErrorExceptionCode: 2Message: mysqli::__construct(): Headers and client library minor version mismatch. Headers:50541 Library:50634File: C:MAMPhtdocstask_managerincludeDbConnect.phpLine: 24Trace#0 [internal function]: SlimSlim::handleErrors(2, ‘mysqli::__const…’, ‘C:\MAMP\htdocs\…’, 24, Array)
    #1 C:MAMPhtdocstask_managerincludeDbConnect.php(24): mysqli->__construct(‘localhost’, ‘guest’, ‘bemyguest’, ‘task_manager’)
    #2 C:MAMPhtdocstask_managerincludeDbHandler.php(18): DbConnect->connect()
    #3 C:MAMPhtdocstask_managerv1index.php(74): DbHandler->__construct()
    #4 [internal function]: {closure}()
    #5 C:MAMPhtdocstask_managerlibsSlimRoute.php(436): call_user_func_array(Object(Closure), Array)
    #6 C:MAMPhtdocstask_managerlibsSlimSlim.php(1307): SlimRoute->dispatch()
    #7 C:MAMPhtdocstask_managerlibsSlimMiddlewareFlash.php(85): SlimSlim->call()
    #8 C:MAMPhtdocstask_managerlibsSlimMiddlewareMethodOverride.php(92): SlimMiddlewareFlash->call()
    #9 C:MAMPhtdocstask_managerlibsSlimMiddlewarePrettyExceptions.php(67): SlimMiddlewareMethodOverride->call()
    #10 C:MAMPhtdocstask_managerlibsSlimSlim.php(1254): SlimMiddlewarePrettyExceptions->call()
    #11 C:MAMPhtdocstask_managerv1index.php(339): SlimSlim->run()
    #12 {main}

  • MS26

    I get this error when ever I try to send a request to the API:
    InvalidArgumentException: Cannot create LogWriter. Invalid resource handle. in C:wamp64wwwapp_devlibsSlimLogWriter.php on line 60

    Is any one able to help?

  • Jeremiah Sekione

    Hey there, where can i get the Task Manager App codes?

    • Saidur Rahman

      I also need App side code.

  • vikrant arankalle

    Hi Ravi getting error 500 Internal Server Error

    Log is
    C:/wamp/www/task_manager/v1/.htaccess: Invalid command ‘.htaccess’, perhaps misspelled or defined by a module not included in the server configuration

    please help

    • vikrant arankalle

      problem soved thanks

      • near

        I got this error too.. how to solve it?

    • How you solved it?

  • amit

    Hi Ravi,

    I did call for post data as given below. I am facing an issue to receive post parameter.

    $requestUrl=’http://localhost/amit/task_manager/v1/tasks’; //Please note 24-MB01 is sku

    $myjson = ‘{“task”:{“name”: [{“sku”:”MY_SKU5″,”quantity”:10}]}}’;

    $productsJson = json_encode($myjson);

    $headers
    = array(“Content-type: application/json”,”Content-Length: ” .
    strlen($myjson),”Authorization: wsiiclqy0kj9qel170f8w6gxxsshc3gx” );
    $ch = curl_init();
    $ch = curl_init($requestUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, “POST”);

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_USERAGENT, ‘Mozilla/5.0’);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($myjson));
    curl_setopt($ch, CURLOPT_VERBOSE, true);

    $result = curl_exec($ch);

    var_dump(curl_getinfo($ch), $result);
    $result= json_decode($result);

    Please help.

    Thanks

  • S Sathiya

    hi ravi,
    thanks for your valuable development support. i have a problem when i publish the api on my server. I am getting the below error while i try the api using postman.

    Call to undefined method mysqli_stmt::get_result() in

    But the same code works fine on localhost xampp server. I tried check the mysqlnd in my server php config. still i am getting the same issue.

    Can you please help me.
    Thanks again.

  • Mehmet CAN

    thank so much for great tutorial. I use react native fetch function for get method but firstly not working and response sad “Api key is missing” (at the same time its working postman 🙂 but not working react-native mobile)
    then in v1/index.php when i changed headers[‘Authorization’] => headers[‘authorization’] its working. Thanks so much brother…

  • near

    is there any download link for project files? I tried the rest api testing like the video, but the respon is 500 internal server error. any suggestion? thx

  • hossein rezaeian

    https://uploads.disquscdn.com/images/b35e9573c95eba7367594a81e06def421211dacafb3f6422aa0c48f40223f728.png hi Ravi
    tanks for This training
    But when I registered user
    Registration is not done
    why?
    please help me

  • Hi Ravi, great tutorial thanks. I download the project and followed in process but i am getting Internal server error. ARC is printing this Log

    500 Internal Server Error

    Internal Server Error
    The server encountered an internal error or
    misconfiguration and was unable to complete
    your request.
    Please contact the server administrator,
    admin@localhost and inform them of the time the error occurred,
    and anything you might have done that may have
    caused the error.
    More information about this error may be available
    in the server error log.

  • Ayush Sharma

    Hi, Ravi sir [pls solve this problem]

    500 Internal Server Error

    Internal Server Error
    The server encountered an internal error or
    misconfiguration and was unable to complete
    your request.
    Please contact the server administrator at
    admin@example.com to inform them of the time this error occurred,
    and the actions you performed just before this error.
    More information about this error may be available
    in the server error log.

  • micthaworm

    if you can do this post in slim 3 that will be great

  • Sandeep Mali

    Hello ,
    I am using xampp for api testing

    http://localhost:81/task_manager/v1/

    I have downloaded project form hive site use ad it is task_manager and created database as per suggestion
    404 not found error..
    I am unable to find solution
    I think may be reason is .htaccess..
    Please Help

  • Sandeep Mali

    require_once ‘../include/DbHandler.php’;
    require_once ‘../include/PassHash.php’;
    require ‘.././libs/Slim/Slim.php’;

    SlimSlim::registerAutoloader();

    Or may there is issue i dnt know