Создание RESTful API с помощью CodeIgniter
Веб-службы RESTful позволяют запрашивать доступ к текстовым представлениям данных и работать с ними, используя определенные наборы методов без сохранения состояния.
В этой статье рассказывается о том, как можно создать RESTful API с методами GET, PUT, POST и DELETE.

Сначала создайте проект CodeIgniter с данными, необходимыми для подключения к базе данных MySQL. Затем:
Шаг 1: Создайте таблицу базы данных MySQL
Создайте таблицу employee для добавления, удаления и отображения информации о сотрудниках с помощью REST API.
CREATE TABLE `employee` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`skills` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`designation` varchar(255) NOT NULL,
`age` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `employee`
ADD PRIMARY KEY (`id`);
ALTER TABLE `employee`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
Шаг 2. Создание файла конфигурации REST API
Теперь нужно создать конфигурационный файл REST application/config/rest.php, используя приведенный ниже код.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['force_https'] = FALSE;
$config['rest_default_format'] = 'json';
$config['rest_supported_formats'] = [
'json',
'array',
'csv',
'html',
'jsonp',
'php',
'serialized',
'xml',
];
$config['rest_status_field_name'] = 'status';
$config['rest_message_field_name'] = 'error';
$config['enable_emulate_request'] = TRUE;
$config['rest_realm'] = 'REST API';
$config['rest_auth'] = FALSE;
$config['auth_source'] = 'ldap';
$config['allow_auth_and_keys'] = TRUE;
$config['auth_library_class'] = '';
$config['auth_library_function'] = '';
$config['rest_valid_logins'] = ['admin' => '1234'];
$config['rest_ip_whitelist_enabled'] = FALSE;
$config['rest_handle_exceptions'] = TRUE;
$config['rest_ip_whitelist'] = '';
$config['rest_ip_blacklist_enabled'] = FALSE;
$config['rest_ip_blacklist'] = '';
$config['rest_database_group'] = 'default';
$config['rest_keys_table'] = 'keys';
$config['rest_enable_keys'] = FALSE;
$config['rest_key_column'] = 'key';
$config['rest_limits_method'] = 'ROUTED_URL';
$config['rest_key_length'] = 40;
$config['rest_key_name'] = 'X-API-KEY';
$config['rest_enable_logging'] = FALSE;
$config['rest_logs_table'] = 'logs';
$config['rest_enable_access'] = FALSE;
$config['rest_access_table'] = 'access';
$config['rest_logs_json_params'] = FALSE;
$config['rest_enable_limits'] = FALSE;
$config['rest_limits_table'] = 'limits';
$config['rest_ignore_http_accept'] = FALSE;
$config['rest_ajax_only'] = FALSE;
$config['rest_language'] = 'english';
$config['check_cors'] = FALSE;
$config['allowed_cors_headers'] = [
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Access-Control-Request-Method'
];
$config['allowed_cors_methods'] = [
'GET',
'POST',
'OPTIONS',
'PUT',
'PATCH',
'DELETE'
];
$config['allow_any_cors_domain'] = FALSE;
$config['allowed_cors_origins'] = [];
Шаг 3. Создание файлов библиотеки REST
Теперь нужно разработать файлы библиотеки для обработки операций веб-сервисов RESTful. Мы создадим application/libraries/Rest_lib.phpи application/libraries/Format.php. Библиотека Rest_lib.php будет расширена в контроллер API Emp.php.
Шаг 4: Создание контроллера REST API
Мы создадим файл application/controllers/api/Emp.php для обработки методов RESTful API, таких как GET, PUT, POST и DELETE.
<?php
require APPPATH . 'libraries/Rest_lib.php';
class Emp extends Rest_lib {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function index_get($id = 0){
if(!empty($id)){
$empData = $this->db->get_where("employee", ['id' => $id])->row_array();
}else{
$empData = $this->db->get("employee")->result();
}
$this->response($empData, Rest_lib::HTTP_OK);
}
public function index_post(){
$postData = $this->input->post();
$this->db->insert('employee',$postData);
$this->response(['Employee created successfully.'], Rest_lib::HTTP_OK);
}
public function index_put($id){
$putData = $this->put();
$this->db->update('employee', $putData, array('id'=>$id));
$this->response(['Employee updated successfully.'], Rest_lib::HTTP_OK);
}
public function index_delete($id){
$this->db->delete('employee', array('id'=>$id));
$this->response(['Employee deleted successfully.'], Rest_lib::HTTP_OK);
}
}
Шаг 5: Запустите RESTful API
Для выполнения операций GET, PUT, POST и DELETE с данными о сотрудниках создается приведенный ниже URL-адрес веб-службы.
https://localhost/demo/restfull_api_codeigniter/api/emp
Теперь выполним запрос к этой веб-службе, используя расширение браузера Postman.
Получение всех записей сотрудников для отображения

Размещение информации о сотруднике для вставки новой записи

Ввод данных для обновления записи о сотруднике

Удаление записи о сотруднике

Заключение
Теперь вы сможете создавать Restful API с помощью фреймворка CodeIgniter, и разрабатывать приложения, выполняя методы GET, PUT, POST, DELETE.