Rosh_LK
Rosh_LK

Reputation: 700

read JSON input in slim framework

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":"[email protected]",
"password":"xxxxxx"
}

can i use verifyRequiredParams(array('name','email', 'password')); and $name = $app->request->post('name'); if request come as a JSON.

Upvotes: 1

Views: 2872

Answers (2)

Rosh_LK
Rosh_LK

Reputation: 700

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();
    }
} 

Upvotes: 0

rbr94
rbr94

Reputation: 2277

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.

Upvotes: 4

Related Questions