Create RESTful API with Code Igniter #8 : Delete user data, Handle CORS and Make the status code dynamic

in #utopian-io6 years ago

Repository

https://github.com/bcit-ci/CodeIgniter

What Will I Learn?

  • Delete user data
  • Handle CORS and Make the status code dynamic

Requirements

  • Basic PHP
  • Install Ci > 3.1
  • Local server (Xampp, Wampp, or etc)
  • Mysqli

Resources

Difficulty

Basic

Tutorial Content

In the previous tutorial, we made a number of things. We have protected our API endpoints with tokens and we have used them to update our data, now we will use it to delete the data that we have. We will also learn new things. That is Cross-Origin Resource Sharing (CORS). Later we will learn how to access our endpoints from other domains. Because if we make an API endpoint, It is possible are we will access the endpoint in various domains. if we don't set CORS then we won't automatically be allowed to access the endpoint.

Delete data

After we have made endpoint updates and endpoint protection, in this tutorial we will learn how to delete data in the database using the endpoints we have created, here is a list of endpoints that we have made in this tutorial series.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

//Routes
$route['api/users']['GET']          = "UsersController/all_users";
$route['api/users/(:num)']['GET']   = "UsersController/detail_user/$1";
$route['api/register']['POST']      = "UsersController/register";
$route['api/user/(:num)']['PUT']    = "UsersController/update/$1";
$route['api/user/(:num)']['DELETE'] = "UsersController/delete/$1";
$route['api/login']['POST']         = "UsersController/login";

//Endpoint to check token
$route['api/check-token']['GET']    = "UsersController/check_token";

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

to delete data we can use the following endpoint $route['api/user/(:num)']['DELETE'] = "UsersController/delete/$1";. We will still use the UsersController.php controller and use the DELETE method. at UsersController.php use the delete function and pass parameters with an integer (int) type "UsersController/delete/$1";.

  • Make the delete function in the controller

As in the routing above, we will access the delete method at UsersController.php, the following is its function:

UsersController.php

public function delete($id) {
        if ($this->protected_method($id)) {
            return $this->response($this->user->delete($id));
        }
    }
  • In this function, we will accept one parameter, namely $id which we will use as a reference for the data to be deleted.

  • Before we delete the data, we need to check whether the user who wants to delete is a valid user. We can check the user's token with the method we made in the previous tutorial, here is a function to check the token.

UsersController.php

public function protected_method($id) {
        if ($id_from_token = $this->check_token()) {
            if ($id_from_token == $id) {
                return true;
            } else {
                return $this->response([
                    'success'   => false,
                    'message'   => "User is different."
                ]);
            }
        }
    }
  • In the protected_method($id) function we will compare the existing $id resulting from decoding the token with the id we received in the $id parameter.

  • If the result id decodes the token and the parameter id is the same $id_from_token == $id, then we will return true.

  • $this->user->delete($id) After we create a function at UsersController.php then we will create the function delete($id) in the User.php model. The following is the function of the User.php model.

public function delete($id) {
        $this->db->where('id', $id); // Where Id to delete data
        //delete the users
        if($this->db->delete('users')) {
            return [
                'status'    => true,
                'message'   => 'Data successfully deleted'
            ];
        }
    }
  • Before deleting we have to specifically choose which data to delete, in this tutorial we will delete based on 'id' $this->db->where('id', $id);

  • We can use the delete('users') function from sql to delete the database, the parameter is the name of table 'users'.

ezgif.com-video-to-gif (6).gif

Handle CORS

We will learn how to handle Cross-Origin Resource Sharing (CORS) on our API, CORS occurs when our API is accessed by another domain that we don't know. Of course, when we make an API there is a possibility that our API will be accessed by another domain. therefore we must handle the CORS problem. We can handle CORS through each controller. Here we will use it in the function __construct ().

  • __construct () function

We will set the header in the __construct () by setting a header, we can use that header on every request in our controller.

UsersContoller.php

// Allowing CORS
      header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
  • Allowing Domain with 'Access-Control-Allow-Origin: *, we use * for allowing all domain.

  • Allowing Methods 'Access-Control-Allow-Methods: GET, PUT, DELETE, OPTIONS', We can choose which method we allow for CORS. The methods are GET, PUT, DELETE, OPTIONS

  • Allowing Headers 'Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description', We can delete the headers that we will allow when requesting API. Example: Content-Type, Content-Range, Content-Disposition, Content-Description.

After we set the header we can try to make a request to one of our APIs, here are the results:

ezgif.com-video-to-gif.gif

Make Response status dynamic

In the last section, we will make the status response dynamic, in the previous tutorial, we have created a function for the response() status but the status given is always 200 (ok). You can see more status code at this link status code.

UsersController.php

public function response($data, $status = 200) {
        $this->output
             ->set_content_type('application/json')
             ->set_status_header($status)
             ->set_output(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
             ->_display();
        exit;
    }
  • This new function we will pass one additional parameter, namely $status and we will set the default status code is 200.

  • We will pass this as a status code parameter that we use to respond to requests from users. The following is how to pass the status when the return response. We will try it at Endpoint login

  • Use of protected_method($id)

public function login() {
        if (!$this->user->is_valid()) {
            return $this->response([
                'success'   => false,
                'message'   => 'Password or Email is wrong'
            ], 401);
        }
    }

We will Return Status 401, Because 401 is the status for Unauthorized the password or email is wrong.

ezgif.com-video-to-gif (1).gif

We can see in the status section we have changed the status to dynamic according to the parameters we passed when running the function response ().

We have learned how to do delete and handle cors and also make the status code dynamic. I hope you understand how to make an API with Code igniter. Thank you for following this tutorial series, hope you can develop it for the better.

Curriculum

Create RESTful API with Code Igniter #1 : Basic installation, Setup configuration and Database, Create Routes API

Create RESTful API with Code Igniter #2 : Create API register, Models and Controllers, JSON Response

Create RESTful API with Code Igniter #3 : Create Endpoint for Users and User detail, Dynamic functions

Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password

Create RESTful API with Code Igniter #5 : Get user data, Encode data, and Generate token

Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid

Create RESTful API with Code Igniter #7 : Update User data and endpoint protection with tokens

Proof of work done

https://github.com/milleaduski/RESTful-CI

Sort:  

Thank you for your contribution @duski.harahap.
We've been reviewing your tutorial and suggest the following points below:

  • Your tutorial is interesting, but this subject is quite easy to find online.

  • Good work on the illustration and structure of your tutorial.

Thanks for your work on developing this great tutorial.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.19
TRX 0.15
JST 0.029
BTC 63525.38
ETH 2645.15
USDT 1.00
SBD 2.76