{"id":28787,"date":"2024-04-16T11:09:09","date_gmt":"2024-04-16T10:09:09","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/desarrollo-de-api-rest-con-codeigniter-4-guia-detallada\/"},"modified":"2024-06-03T18:40:52","modified_gmt":"2024-06-03T17:40:52","slug":"desarrollo-de-api-rest-con-codeigniter-4-guia-detallada","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/","title":{"rendered":"REST API Development with CodeIgniter 4: Detailed Guide"},"content":{"rendered":"<p>The development of REST APIs has taken on crucial importance in the world of web development, allowing communication between different software systems. CodeIgniter 4, being one of the lightest and fastest PHP frameworks, offers an excellent platform for building powerful and efficient REST APIs. In this tutorial, we&#039;ll explore how you can develop a REST API using CodeIgniter 4, ranging from initial setup to advanced methods to secure and optimize your API.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Configuracion_Inicial_de_CodeIgniter_4\" >CodeIgniter 4 Initial Configuration<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Instalacion_de_CodeIgniter_4\" >Installing CodeIgniter 4<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Configuracion_de_la_Base_de_Datos\" >Database Configuration<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Estructura_de_Directorios_Importantes\" >Important Directory Structure<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Creacion_de_la_API_REST\" >Creating the REST API<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Definicion_de_Rutas\" >Definition of Routes<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Creacion_de_Controladores\" >Controller Creation<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Modelos_y_Acceso_a_la_Base_de_Datos\" >Models and Access to the Database<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Seguridad_y_Mejoras\" >Security and Improvements<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Seguridad_con_JWT\" >Security with JWT<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Caching\" >Caching<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Manejo_de_Errores\" >Error Handling<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/nelkodev.com\/en\/php\/rest-api-development-with-codeigniter-4-detailed-guide\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Configuracion_Inicial_de_CodeIgniter_4\"><\/span>CodeIgniter 4 Initial Configuration<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Before we dive into the heart of creating APIs, we need to prepare our development environment. Here I will guide you through the installation and initial configuration of CodeIgniter 4.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Instalacion_de_CodeIgniter_4\"><\/span>Installing CodeIgniter 4<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>You can install CodeIgniter 4 by downloading it directly from its official site or using Composer, a dependency manager for PHP. I recommend using Composer, as it makes it easy to manage dependencies and update the framework. Run the following command to install CodeIgniter 4 with Composer:<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">composer create-project codeigniter4\/appstarter your-project-api<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Configuracion_de_la_Base_de_Datos\"><\/span>Database Configuration<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>CodeIgniter 4 simplifies your database configuration. Simply edit the file <code>app\/Config\/Database.php<\/code> and configure the connection parameters according to your database manager. Essentially, you will need to provide details such as hostname, username, password, and database name.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Estructura_de_Directorios_Importantes\"><\/span>Important Directory Structure<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li><strong>app\/Controllers<\/strong>: Here you will create the controllers for your API.<\/li>\n<li><strong>app\/Models<\/strong>: The models that interact with the database.<\/li>\n<li><strong>app\/config<\/strong>: General framework settings.<\/li>\n<li><strong>public<\/strong>: Public directory from which files are served.<\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Creacion_de_la_API_REST\"><\/span>Creating the REST API<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Creating an API in CodeIgniter 4 involves defining routes, controllers, and possibly models if you interact with a database. We are going to develop a simple API to manage users.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Definicion_de_Rutas\"><\/span>Definition of Routes<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Edit the file <code>app\/Config\/Routes.php<\/code> to define your API routes. For example, for a users resource, you can configure routes like these:<\/p>\n<pre><code class=\"&quot;language-php&quot;\">$routes-&gt;group(&#039;api&#039;, function ($routes) { $routes-&gt;resource(&#039;users&#039;); });<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Creacion_de_Controladores\"><\/span>Controller Creation<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In CodeIgniter 4, each action in your API will be handled by methods in a controller. Create a new controller in <code>app\/Controllers\/Users.php<\/code>. Here is an example of how you could structure the controller to handle CRUD operations:<\/p>\n<pre><code class=\"&quot;language-php&quot;\">namespace AppControllers; use CodeIgniterRESTfulResourceController; class Users extends ResourceController { protected $modelName = &#039;AppModelsUserModel&#039;; protected $format = &#039;json&#039;; public function index() { return $this-&gt;respond($this-&gt;model-&gt;findAll()); } }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Modelos_y_Acceso_a_la_Base_de_Datos\"><\/span>Models and Access to the Database<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Generally, in an API, you will interact with a database. The Model in CodeIgniter encapsulates database operations. For example, for the users resource, the model might look like this:<\/p>\n<pre><code class=\"&quot;language-php&quot;\">namespace AppModels; use CodeIgniterModel; class UserModel extends Model { protected $table = &#039;users&#039;; protected $primaryKey = &#039;id&#039;; protected $allowedFields = [&#039;name&#039;, &#039;email&#039;]; \/\/ fields allowed to insert and update }<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Seguridad_y_Mejoras\"><\/span>Security and Improvements<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Once your API is up and running, it is essential to consider security and performance aspects.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Seguridad_con_JWT\"><\/span>Security with JWT<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To secure your API, you can use JSON Web Tokens (JWT). This involves modifying the handlers to check the validity of the token on each request. Implementing JWT can provide a robust layer of security by authenticating and authorizing requests.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Caching\"><\/span>Caching<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To improve performance, consider implementing caching for your API responses. CodeIgniter 4 offers built-in support for different cache drivers, which can be configured in <code>app\/Config\/Cache.php<\/code>.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Manejo_de_Errores\"><\/span>Error Handling<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Properly handling errors is crucial to maintaining the robustness of your API. Make sure you use the methods <code>failNotFound()<\/code> for resources not found, and <code>failValidationErrors()<\/code> for data validation errors.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Creating a REST API with CodeIgniter 4 can be a rewarding and educational process, offering precise control over your application&#039;s logic and interaction with other platforms or services. By following the steps in this tutorial, you should be on your way to developing robust and efficient REST APIs.<\/p>\n<p>For more information and other related tutorials, feel free to visit <a href=\"https:\/\/nelkodev.com\/en\/\">NelkoDev<\/a> and for any questions, find my contact details at <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">this page<\/a>.<\/p>","protected":false},"excerpt":{"rendered":"<p>REST API development has become crucial in the world of web development, allowing communication between different software systems. CodeIgniter 4, being one of the lightest and fastest PHP frameworks, offers an excellent platform for building powerful and efficient REST APIs. In this tutorial, we will explore how you can develop a REST API [\u2026]<\/p>","protected":false},"author":1,"featured_media":28788,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2206,420,1913],"tags":[667,1344,205,233,90,211,1602,358,15,1008,1325],"class_list":["post-28787","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php","category-blog","category-pruebas-de-backend","tag-api","tag-backend","tag-blog","tag-codeigniter","tag-con","tag-desarrollo","tag-detallada","tag-guia","tag-php","tag-pruebas","tag-rest"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28787","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=28787"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28787\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/28788"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=28787"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=28787"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=28787"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}