read JSON input in slim framework - php

i am new to slim framework following a tutorial i managed to get post data to my API.but when i tried to send data as JSON it gives me an error.I tried to accpt JSON request as follows what is the correct syntax to achive this.i get error as Required field(s) name, email, password is missing or empty
$app->post('/login', function() use ($app) {
// check for required params
$json = $app->request->getBody();
$data = json_decode($json, true);
verifyRequiredParams(array('name','email', 'password'));
how i can get json data from a post request in my API from an JSON array like
{
"name":"usertest",
"email":"xxxx#xxx.xxx",
"password":"xxxxxx"
}
can i use verifyRequiredParams(array('name','email', 'password')); and $name = $app->request->post('name'); if request come as a JSON.

To read the request data you can use your $data property. It should be an object so you can use it like this:
$name = $data->name;
$email = $data->email;
EDIT:
Use $data = json_decode($json) instead of $data = json_decode($json, true) to convert the json data to object instead of an associative array.

the problem was with placing my verifyRequiredParams function i think.i fixed the issue from following code in case any one had same issue.
$app->post('/login', function() use ($app) {
if($app->request->headers->get('Content-Type')=='application/json'){
$json = $app->request->getBody();
verifyRequiredParamsjson(array('email','password'),$json);
$data = json_decode($json);
// check for required params
$email = $data->email;
$password = $data->password;
}
else{
// 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{
$response['error'] = true;
$response['message'] = 'Login failed. Incorrect credentials';
}
echoRespnse(200, $response);
});
required parameter check,
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();
}
}

Related

Postman giving error 422 when passing parameters in POST request to PHP API setup on SLIM framework

I setup a PHP API on Slim 3 framework. I have followed its documents. I am sending POST request from POSTMAN to check it on localhost, being run by XAMPP. But it is giving errors that required parameters are empty or missing though I am giving all the parameters in the POST request, as shown in the attached photo. enter image description here
I have checked the related code in index.php and Dboperations.php , and didn't find any error. The code is also written here:
$app = new \Slim\App([
'settings'=>[
'displayErrorDetails'=>true
]
]);
$app->post('/createuser', function(Request $request, Response $response){
if(!haveEmptyParameters(array('firstname', 'surname', 'email', 'fanID', 'deviceLocation'), $request, $response)){
$request_data = $request->getParsedBody();
$firstname = $request_data['firstname'];
$surname = $request_data['surname'];
$email = $request_data['email'];
$fanID = $request_data['fanID'];
$deviceLocation = $request_data['deviceLocation'];
$db = new DbOperations;
$result = $db->createUser($firstname, $surname, $email, $fanID, $deviceLocation);
if($result == USER_CREATED){
$message = array();
$message['error'] = false;
$message['message'] = 'User created successfully';
$response->write(json_encode($message));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(201);
}else if($result == USER_FAILURE){
$message = array();
$message['error'] = true;
$message['message'] = 'Some error occurred';
$response->write(json_encode($message));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
}else if($result == USER_EXISTS){
$message = array();
$message['error'] = true;
$message['message'] = 'User Already Exists';
$response->write(json_encode($message));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
}
}
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
});
function haveEmptyParameters($required_params, $request, $response){
$error = false;
$error_params = '';
$request_params = $request->getParsedBody();
foreach($required_params as $param){
if(!isset($request_params[$param]) || strlen($request_params[$param])<=0){
$error = true;
$error_params .= $param . ', ';
}
}
if($error){
$error_detail = array();
$error_detail['error'] = true;
$error_detail['message'] = 'Required parameters ' . substr($error_params, 0, -2) . ' are
missing or empty';
$response->write(json_encode($error_detail));
}
return $error;
}
$app->run();
I have used the same parameters e.g firstname,surname etc in Dboperations.php file so I am not attaching the code from that php script.Kindly consider guiding me on this problem.

How to stop getting 'Required parameters' missing error when POST data using retrofit Android as POSTMAN does not showing this error?

I created a slim framework backend support for my app and i define a function which needs to check if parameters that are going to be POSTED,matching the required parameters to be posted.Now,when i send a POST request using POSTMAN, it is executed well.But when i send request using retrofit in my android app then it the 'required parameters are missing'.
I tried converting json_decode() to decode the data when requesting parameters are passed to checkIfEmpty function.
class CheckEmptyParams{
function paramsCheck($required_params,$request,$response){
$error = false;
$error_params = '';
$request_params = $request->getParsedBody();
foreach($required_params as $param){
if(!isset($request_params[$param]) || strlen($request_params[$param])<0){
$error = true;
$error_params .= $param . ',';
}
}
if($error){
$error_detail = array();
$error_detail['error'] = true;
$error_detail['message'] = 'Required Parameters are missing- ' .substr($error_params,0,-1);
$response->write(json_encode($error_detail));
$response->withHeader('Content-Type','application/json')
->withStatus(422);
}
return $error;
}
}
$app->post('/userlogin',function(Request $request,Response $response){
$params_check = new CheckEmptyParams;
if(!$params_check->paramsCheck(array('email','password'),$request,$response)){
$request_data = $request->getParsedBody();
$email = $request_data['email'];
$password = $request_data['password'];
$db = new DbOperations;
$result = $db->userLogin($email,$password);
if($result == USER_AUTHENTICATED){
$response_data = array();
$response_data['error'] = false;
$response_data['message'] = 'User Authentication Successful';
$response->write(json_encode($response_data));
return $response->withHeader('Content-Type','application/json')
->withStatus(200);
}
else if($result == USER_NOT_FOUND){
$response_data = array();
$response_data['error'] = true;
$response_data['message'] = 'User not found';
$response->write(json_encode($response_data));
return $response->withHeader('Content-Type','application/json')
->withStatus(422);
}
else if($result == USER_PASSWORD_DO_NOT_MATCH){
$response_data = array();
$response_data['error'] = true;
$response_data['message'] = 'Password do not match';
$response->write(json_encode($response_data));
return $response->withHeader('Content-Type','application/json')
->withStatus(422);
}
$response_data = array();
$response_data['error'] = true;
$response_data['message'] = 'Some error occured';
$response->write(json_encode($response_data));
return $response->withHeader('Content-Type','application/json')
->withStatus(422);
}});
I expect the output to be false as boolean value returned by this function when sending POST request using retrofit.
Android code -
public interface ApiServices {
#Headers({"Content-Type:application/json"})
#FormUrlEncoded
#POST("userlogin")
Call<LoginModel> getLoginData(#Field("email")String email,
#Field("password")String password);
}
private void login(String email,String password){
final Snackbar mLoading = Snackbar.make(mFrameLayout,"Logging in...Please wait",Snackbar.LENGTH_INDEFINITE);
mLoading.show();
ApiClient.getInstance().getApi().getLoginData(email,password).enqueue(new Callback<LoginModel>() {
#Override
public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
if(getActivity()!=null && isAdded()) {
if(response.isSuccessful()){
mLoading.dismiss();
if(response.code()==200){
if(!response.body().isError()){
Snackbar.make(mFrameLayout,response.body().getMessage(),Snackbar.LENGTH_INDEFINITE).show();
}
else{
Snackbar.make(mFrameLayout,response.body().getMessage(),Snackbar.LENGTH_SHORT).show();
}
}
else if(response.code()==422){
Snackbar.make(mFrameLayout, getResources().getString(R.string.text_server_down_error), Snackbar.LENGTH_SHORT).show();
}
}
else{
mLoading.dismiss();
Snackbar.make(mFrameLayout, getResources().getString(R.string.text_server_connection_error),Snackbar.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<LoginModel> call, Throwable t) {
mLoading.dismiss();
if(getActivity()!=null&& isAdded()){
Snackbar.make(mFrameLayout, getResources().getString(R.string.text_server_connection_fail),Snackbar.LENGTH_SHORT).show();
}
}
});
}
Request is being send in POSTMAN but not in android app.
Request being send in POSTMAN

Slim-3 php framework shows page not found error even the url is correct?

Slim-3 php framework shows page not found error even the url is correct.
I am writing webservice for android application in php using slim3 framework.
few days before it was working fine.same code is not working now.It always returns page not found.i think error in the index.php file but i can't figure it out.
I have tried almost anything that i can get to solve this problem.
I changed the directory structure and .htaccess file but still not solved.i am using xampp server.
index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../ChickenShop/vendor/autoload.php';
require_once '../ChickenShop/public/includes/DbOperations.php';
//Creating a new app with the config to show errors
$app = new \Slim\App([
'settings' => [
'displayErrorDetails' => true
]
]);
//registering a new user
$app->post('/register', function (Request $request, Response $response) {
if (isTheseParametersAvailable(array('name', 'email', 'password', 'phone','address'))) {
$requestData = $request->getParsedBody();
$name = $requestData['name'];
$email = $requestData['email'];
$password = $requestData['password'];
$phone = $requestData['phone'];
$address = $requestData['address'];
$db = new DbOperations();
$responseData = array();
$result = $db->registerUser($name, $email, $password, $phone, $address);
if ($result == USER_CREATED) {
$responseData['error'] = false;
$responseData['message'] = 'Registered successfully';
$responseData['user'] = $db->getUserByEmail($email);
} elseif ($result == USER_CREATION_FAILED) {
$responseData['error'] = true;
$responseData['message'] = 'Some error occurred';
} elseif ($result == USER_EXIST) {
$responseData['error'] = true;
$responseData['message'] = 'This email already exist, please login';
}
$response->getBody()->write(json_encode($responseData));
}
});
//user login route
$app->post('/login', function (Request $request, Response $response) {
if (isTheseParametersAvailable(array('email', 'password'))) {
$requestData = $request->getParsedBody();
$email = $requestData['email'];
$password = $requestData['password'];
$db = new DbOperations();
$responseData = array();
if ($db->userLogin($email, $password)) {
$responseData['error'] = false;
$responseData['user'] = $db->getUserByEmail($email);
} else {
$responseData['error'] = true;
$responseData['message'] = 'Invalid email or password';
}
$response->getBody()->write(json_encode($responseData));
}
});
//getting all products
$app->get('/products', function (Request $request, Response $response) {
$db = new DbOperations();
$products = $db->getAllProducts();
$response->getBody()->write(json_encode(array("products" => $products)));
});
//function to check parameters
function isTheseParametersAvailable($required_fields)
{
$error = false;
$error_fields = "";
$request_params = $_REQUEST;
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
$response = array();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echo json_encode($response);
return false;
}
return true;
}
// Run app
$app->run();
URL that i have tried to access:
http://localhost/ChickenShop/public/
Content of .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
i expected it to work fine.

Cannot get response from PUT request using Slim Framework

Am trying to update an existing entity in my database using PUT request but i have 2 issues, when am calling the request from phpStorm rest client debugger am getting an error
{"error":true,"message":"Required field(s) restaurant_id, service_rating, food_rating, music_rating is missing or empty"}
when i call the same request from Advance rest client addon on google chrome am getting
{"error":true,"message":"Task failed to update. Please try again!"}
so i can't understand if the real bug is on the verifyRequiredParams or in my function implementation . Am providing the code if someone can help me.
This is my index.php file
$app->put('/userRatings/:rating_id', 'authenticate', function($rating_id) use($app) {
// check for required params
verifyRequiredParams(array('restaurant_id', 'service_rating', 'food_rating', 'music_rating'));
global $user_id;
$restaurant_id = $app->request->put('restaurant_id');
$service_rating = $app->request->put('service_rating');
$food_rating = $app->request->put('food_rating');
$music_rating = $app->request->put('music_rating');
$db = new DbHandler();
$response = array();
// updating rating
$result = $db->updateRating($user_id, $rating_id, $restaurant_id, $service_rating, $food_rating, $music_rating);
if ($result) {
// rating 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);
});
This is the function code for the verifyRequiredParams which is located in the index.php file
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();
}
}
And this is my DbHandler.php file where the function is located.
public function updateRating( $user_id, $rating_id, $restaurant_id, $service_rating, $food_rating, $music_rating) {
$stmt = $this->conn->prepare("UPDATE user_ratings set service_rating = ?, food_rating = ?, music_rating = ? WHERE user_id = ? AND rating_id = ? AND restaurant_id = ?");
$stmt->bind_param("iiiiii", $user_id , $rating_id, $restaurant_id, $service_rating, $food_rating, $music_rating);
$stmt->execute();
$num_affected_rows = $stmt->affected_rows;
$stmt->close();
return $num_affected_rows > 0;
}
All my connections are ok i have checked them and also my other services are working fine
The two errors was because advance rest client use "PUT" with capital letters and php storm with lower characters even if its written with capital in php storm i notice that by changing "PUT" with "put" in the if statement of verifyRequiredParams function and now its working and updating perfectly
Add bellow code in your index.php file
$app->addBodyParsingMiddleware();

Rest API and 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 ?
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.
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
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
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!

Categories