Rest API和Slim Framework

I follow the tutorial here :

http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23/

So I have in my index.php :

<?php

error_reporting(-1);
ini_set('display_errors', 'On');

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

$app = new Slim();

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

/**
 * 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::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_id = $db->getUserId($api_key);
        }
    } else {
        // api key is missing in header
        $response["error"] = true;
        $response["message"] = "Api key is misssing";
        echoRespnse(400, $response);
        $app->stop();
    }
}

/**
 * ----------- METHODS WITHOUT AUTHENTICATION ---------------------------------
 */
/**
 * 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";
            } else if ($res == USER_CREATE_FAILED) {
                $response["error"] = true;
                $response["message"] = "Oops! An error occurred while registereing";
            } else if ($res == USER_ALREADY_EXISTED) {
                $response["error"] = true;
                $response["message"] = "Sorry, this email already existed";
            }
            // echo json response
            echoRespnse(201, $response);
        });

/**
 * 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);
        });

/*
 * ------------------------ METHODS WITH AUTHENTICATION ------------------------
 */

/**
 * 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);
        });

/**
 * 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);
            }
        });

/**
 * 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;
                echoRespnse(201, $response);
            } else {
                $response["error"] = true;
                $response["message"] = "Failed to create task. Please try again";
                echoRespnse(200, $response);
            }            
        });

/**
 * 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);
        });

/**
 * 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);
        });

/**
 * 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::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::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::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::getInstance();
    // Http response code
    $app->status($status_code);

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

    echo json_encode($response);
}

$app->run();
?>

But, like others people, I've got some error when I try to call the register method :

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

It seems that $_REQUEST is empty so the parameters are not sent... I try with curl or with RestClient app extension in Google Chrome, it still doesn't work...

Any idea to make it work ?

4个回答



你应该删除'。' 在DbConnect.php和DbHandler.php中</ p>

DbConnect.php </ strong> </ p>

  include_once dirname(__ FILE__)。  ” ./Config.php';

-> include_once dirname(__ FILE__)。 '/Config.php';


nn

DbHandler.php


nn
include_once dirname  (__FILE__)。  ” ./Config.php';

-> include_once dirname(__ FILE__)。 '/Config.php';
</ code> </ pre>
nn

这使得2个文件包含他们需要的内容。 我对此进行了更改,API运行良好。</ p>

注意</ strong>:您应该在通过Chrome插件调用api时添加标头。
Content-Type:application / x-www-form-urlencoded
</ p>
</ div>

展开原文

原文

You should remove '.' in DbConnect.php and DbHandler.php

DbConnect.php

include_once dirname(__FILE__) . './Config.php';

-> include_once dirname(__FILE__) . '/Config.php';

DbHandler.php

include_once dirname(__FILE__) . './Config.php';

-> include_once dirname(__FILE__) . '/Config.php';

That make 2 file include exact what they need. I change this and the API run very good.

Note: You should add header when you call api by Chrome add-on. Content-Type: application/x-www-form-urlencoded enter image description here



另一种访问post params的方法是:</ p>

   //阅读post params 
$ name = $ app-&gt; request-&gt; params('name');
$ email = $ app-&gt; request-&gt; params('email');
$ 密码= $ app-&gt; request-&gt; params('password');
</ code> </ pre>

你得到的回复</ p>

  {
error:true
message:“必填字段名称,电子邮件,密码丢失或为空”
}
</ code> </ pre>

表示您的 帖子参数为空。 尝试使用 Postman - REST Client 来测试您的REST API调用。 使用Firefox附加组件时我遇到了同样的问题“Poster”</ em> </ p>

注意:在测试api时,请确保正确发出POST请求 而不是GET请求。</ strong> </ p>
</ div>

展开原文

原文

Another way of accessing the post params, which worked for me is:

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

And the response you got

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

means your post parameters are empty. Try using Postman - REST Client to test your REST API calls. I faced the same problem while using Firefox Add-On "Poster"

Note: while testing the api make sure you are properly making a POST request and not GET request.



您需要解析php输入流中的原始数据。</ p>

  if(  !empty($ _ GET)){
$ _INPUT = $ _GET;
} else {
$ _INPUT = json_decode(file_get_contents('php:// input'),TRUE);
}
</ code > </ pre>

请参阅
</ p>
</ div >

展开原文

原文

You need to parse the raw data from php input stream.

if (!empty($_GET)) {
    $_INPUT = $_GET;
} else {
    $_INPUT = json_decode(file_get_contents('php://input'), TRUE);
}

see this and this



我使用firefox和POSTER插件来测试REST API。 我从工具 - >海报打开海报窗口后。 在url中将我的路径放到www / task_manager / v1 / register并在参数选项卡中,我传递了三个参数名称,电子邮件,密码,然后我从参数中单击body并单击post按钮。 </ p>

它对我有用。 我看到了很好的结果。</ p>

注意:</ em>

我不能使用chrome高级REST,因为不明原因chrome没有让我安装那个插件! </ p>
</ div>

展开原文

原文

I used firefox and POSTER addon for test REST API. After I open poster window from tools->poster. In the url put my path to www/task_manager/v1/register and in parameters tab I pass three parameter for name, email, password and after that I click on body from parameters and click post button.

its worked for me. and i saw good result.

Note:
I cant use chrome advanced REST, because for unknown reason chrome didnt let me to install that addon!

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐