• How to create REST API for Android app using PHP, Slim and MySQL – Day 4/5

    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.
    index.php
    /**
     * 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
    MethodPOST
    Paramsname, 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.
    index.php
    /**
     * 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
    MethodPOST
    Paramsemail, 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"
    }

  • 0 comments:

    Post a Comment

    FAVOURITE LINE

    To steal ideas from one is plagiarism. To steal from many is Research.

    ADDRESS

    Mumbai , Maharashtra

    EMAIL

    shikha.pathak6@gmail.com
    shikha.the.swt.pari@gmail.com

    Skype

    shikha_pari