How to make simple REST API in Codeignter.
Here is a step-by-step guide to creating a simple REST API in CodeIgniter:
-
Install CodeIgniter: You can download the latest version of CodeIgniter from the official website and extract it to your local development environment.
-
Enable RESTful API in CodeIgniter: To enable RESTful API in CodeIgniter, you need to enable the REST module in the
**application/config/config.php**
file. You can do this by setting
$config['enable_hooks'] = TRUE;
and
$config['rest_enable_keys'] = TRUE;.
Create a Controller: Next, create a controller in the **application/controllers**
directory. This controller will handle the incoming API requests and return the appropriate response.
Define the RESTful API Routes: In the controller, you need to define the routes for your RESTful API. You can do this using the **$route**
array in the **application/config/routes.php**
file. For example, if you want to create a route for the **/users**
endpoint, you can add the following code:
Create the API Methods: In the controller, you need to create the methods for each of the API endpoints. For example, for the **/users**
endpoint, you can create the following methods:
$route['api/users']['GET'] = 'api/users/index';
$route['api/users/(:num)']['GET'] = 'api/users/view/$1';
$route['api/users']['POST'] = 'api/users/create';
$route['api/users/(:num)']['PUT'] = 'api/users/update/$1';
$route['api/users/(:num)']['DELETE'] = 'api/users/delete/$1';
Create the API Methods: In the controller, you need to create the methods for each of the API endpoints. For example, for the **/users**
endpoint, you can create the following methods:
public function index()
{
// code to fetch all users
}
public function view($id)
{
// code to fetch a single user
}
public function create()
{
// code to create a new user
}
public function update($id)
{
// code to update an existing user
}
public function delete($id)
{
// code to delete a user
}
Test the API: Finally, test your API by making requests to the endpoint using a REST client, such as Postman or Insomnia. You can test the different HTTP methods (GET, POST, PUT, DELETE) to ensure that the API is working as expected.
This is a simple example to get started with a RESTful API in CodeIgniter. You can expand this example to include more endpoints, authentication, and validation as needed.
@abcd 1 days ago
Aquí los que apoyamos a Los del limit desde sus inicios..