create account

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

View this thread on steemit.com
· @duski.harahap ·
$41.52
Create RESTful API with Code Igniter #8 : Delete user data, Handle CORS and Make the status code dynamic
#### 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
- Code igneter - https://www.codeigniter.com/
- JSON Web tokens - https://jwt.io/

#### Difficulty
Basic

### Tutorial Content

In the previous [tutorial](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508), 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";```.
<br>

- **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](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508), 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](https://ipfs.busy.org/ipfs/QmVTxHgACnqrQGgY8gU9V4RAuuNEkwNQje8Sgm8wKiP6gQ)
<br>
### 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](https://ipfs.busy.org/ipfs/Qmeg54qBP7ybtSJfSStz7mP7GoZdBqhKbFJWVqSHgw2mQv)

### 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](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes).

**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](https://ipfs.busy.org/ipfs/QmNaPZFr4yHifvbqMrz9yKgGzfAqv5b5GdddgtcX1QSLmv)

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](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-1-basic-installation-setup-configuration-and-database-create-routes-api-1539354852182)

[Create RESTful API with Code Igniter #2 : Create API register, Models and Controllers, JSON Response](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-2-create-api-register-models-and-controllers-json-response-1539531957770)

[Create RESTful API with Code Igniter #3 : Create Endpoint for Users and User detail, Dynamic functions](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-3-create-endpoint-for-user-dan-user-detail-dynamic-functions-1539784449409)

[Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111)

[Create RESTful API with Code Igniter #5 : Get user data, Encode data, and Generate token](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-5-get-user-data-encode-data-and-generate-token-1540704402037)

[Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140)

[Create RESTful API with Code Igniter #7 : Update User data and endpoint protection with tokens](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508)




#### Proof of work done
https://github.com/milleaduski/RESTful-CI
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (37)
authorduski.harahap
permlinkcreate-restful-api-with-code-igniter-8-delete-user-data-handle-cors-and-make-the-status-code-dynamic-1541514183946
categoryutopian-io
json_metadata{"app":"steeditor/0.1.2","format":"markdown","image":["https://ipfs.busy.org/ipfs/QmPLB4NCbcT7XmVPNJkWEXsrvHDfSyZZvCeios9A5VW6c4","https://ipfs.busy.org/ipfs/QmVTxHgACnqrQGgY8gU9V4RAuuNEkwNQje8Sgm8wKiP6gQ","https://ipfs.busy.org/ipfs/Qmeg54qBP7ybtSJfSStz7mP7GoZdBqhKbFJWVqSHgw2mQv","https://ipfs.busy.org/ipfs/QmNaPZFr4yHifvbqMrz9yKgGzfAqv5b5GdddgtcX1QSLmv"],"tags":["utopian-io","tutorials","php","codeigneter"],"users":["duski"],"links":["https://github.com/bcit-ci/CodeIgniter","https://www.codeigniter.com/","https://jwt.io/","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508","https://en.wikipedia.org/wiki/List_of_HTTP_status_codes","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-1-basic-installation-setup-configuration-and-database-create-routes-api-1539354852182","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-2-create-api-register-models-and-controllers-json-response-1539531957770","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-3-create-endpoint-for-user-dan-user-detail-dynamic-functions-1539784449409","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-5-get-user-data-encode-data-and-generate-token-1540704402037","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140","https://github.com/milleaduski/RESTful-CI"]}
last_update2018-11-06 14:23:09
created2018-11-06 14:23:09
active2018-11-09 18:55:57
last_payout2018-11-13 14:23:09
depth0
children4
net_rshares0
vote_rshares0
children_abs_rshares0
cashout_time1969-12-31 23:59:59
max_cashout_time1969-12-31 23:59:59
total_vote_weight0
reward_weight10,000
total_payout_value31.156 SBD
curator_payout_value10.362 SBD
author_rewards41,990
net_votes61
root_authorduski.harahap
root_permlinkcreate-restful-api-with-code-igniter-8-delete-user-data-handle-cors-and-make-the-status-code-dynamic-1541514183946
max_accepted_payout100,000.000 SBD
percent_steem_dollars10,000
allow_repliestrue
allow_votestrue
allow_curation_rewardstrue
beneficiaries
0.
accountutopian.pay
weight500
root_title"Create RESTful API with Code Igniter #8 : Delete user data, Handle CORS and Make the status code dynamic"
pending_payout_value0.000 SBD
total_pending_payout_value0.000 STEEM
author_reputation21,745,256,600,236
promoted0.000 SBD
body_length0
reblogged_by[]
author_curate_reward""
vote details (61)
@portugalcoin ·
$7.51
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](https://join.utopian.io/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](https://review.utopian.io/result/8/21111413).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , ,
properties (37)
authorportugalcoin
permlinkre-duskiharahap-create-restful-api-with-code-igniter-8-delete-user-data-handle-cors-and-make-the-status-code-dynamic-1541514183946-20181106t205921096z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["duski.harahap"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/21111413","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
last_update2018-11-06 20:59:21
created2018-11-06 20:59:21
active2018-11-09 18:55:57
last_payout2018-11-13 20:59:21
depth1
children1
net_rshares0
vote_rshares0
children_abs_rshares0
cashout_time1969-12-31 23:59:59
max_cashout_time1969-12-31 23:59:59
total_vote_weight0
reward_weight10,000
total_payout_value5.684 SBD
curator_payout_value1.828 SBD
author_rewards7,704
net_votes11
root_authorduski.harahap
root_permlinkcreate-restful-api-with-code-igniter-8-delete-user-data-handle-cors-and-make-the-status-code-dynamic-1541514183946
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
allow_repliestrue
allow_votestrue
allow_curation_rewardstrue
beneficiaries[]
root_title"Create RESTful API with Code Igniter #8 : Delete user data, Handle CORS and Make the status code dynamic"
pending_payout_value0.000 SBD
total_pending_payout_value0.000 STEEM
author_reputation38,330,065,267,548
promoted0.000 SBD
body_length0
reblogged_by[]
author_curate_reward""
vote details (11)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (36)
authorutopian-io
permlinkre-re-duskiharahap-create-restful-api-with-code-igniter-8-delete-user-data-handle-cors-and-make-the-status-code-dynamic-1541514183946-20181106t205921096z-20181109t185555z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
last_update2018-11-09 18:55:57
created2018-11-09 18:55:57
active2018-11-09 18:55:57
last_payout2018-11-16 18:55:57
depth2
children0
net_rshares0
vote_rshares0
children_abs_rshares0
cashout_time1969-12-31 23:59:59
max_cashout_time1969-12-31 23:59:59
total_vote_weight0
reward_weight10,000
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
author_rewards0
net_votes0
root_authorduski.harahap
root_permlinkcreate-restful-api-with-code-igniter-8-delete-user-data-handle-cors-and-make-the-status-code-dynamic-1541514183946
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
allow_repliestrue
allow_votestrue
allow_curation_rewardstrue
beneficiaries[]
root_title"Create RESTful API with Code Igniter #8 : Delete user data, Handle CORS and Make the status code dynamic"
pending_payout_value0.000 SBD
total_pending_payout_value0.000 STEEM
author_reputation114,204,278,217,803
promoted0.000 SBD
body_length0
reblogged_by[]
@steem-ua ·
#### 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](https://discord.gg/KpBNYGz)**
properties (36)
authorsteem-ua
permlinkre-create-restful-api-with-code-igniter-8-delete-user-data-handle-cors-and-make-the-status-code-dynamic-1541514183946-20181106t212330z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
last_update2018-11-06 21:23:33
created2018-11-06 21:23:33
active2018-11-06 21:23:33
last_payout2018-11-13 21:23:33
depth1
children0
net_rshares0
vote_rshares0
children_abs_rshares0
cashout_time1969-12-31 23:59:59
max_cashout_time1969-12-31 23:59:59
total_vote_weight0
reward_weight10,000
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
author_rewards0
net_votes0
root_authorduski.harahap
root_permlinkcreate-restful-api-with-code-igniter-8-delete-user-data-handle-cors-and-make-the-status-code-dynamic-1541514183946
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
allow_repliestrue
allow_votestrue
allow_curation_rewardstrue
beneficiaries[]
root_title"Create RESTful API with Code Igniter #8 : Delete user data, Handle CORS and Make the status code dynamic"
pending_payout_value0.000 SBD
total_pending_payout_value0.000 STEEM
author_reputation18,859,335,461,985
promoted0.000 SBD
body_length0
reblogged_by[]
@utopian-io ·
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](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

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

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (36)
authorutopian-io
permlinkre-create-restful-api-with-code-igniter-8-delete-user-data-handle-cors-and-make-the-status-code-dynamic-1541514183946-20181107t181228z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
last_update2018-11-07 18:12:30
created2018-11-07 18:12:30
active2018-11-07 18:12:30
last_payout2018-11-14 18:12:30
depth1
children0
net_rshares0
vote_rshares0
children_abs_rshares0
cashout_time1969-12-31 23:59:59
max_cashout_time1969-12-31 23:59:59
total_vote_weight0
reward_weight10,000
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
author_rewards0
net_votes0
root_authorduski.harahap
root_permlinkcreate-restful-api-with-code-igniter-8-delete-user-data-handle-cors-and-make-the-status-code-dynamic-1541514183946
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
allow_repliestrue
allow_votestrue
allow_curation_rewardstrue
beneficiaries[]
root_title"Create RESTful API with Code Igniter #8 : Delete user data, Handle CORS and Make the status code dynamic"
pending_payout_value0.000 SBD
total_pending_payout_value0.000 STEEM
author_reputation114,204,278,217,803
promoted0.000 SBD
body_length0
reblogged_by[]