#### 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