Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating RESTful API by using pure CodeIgniter?

I need to create a RESTful web api using only CodeIgniter. I can not use any third-party plugins or libraries to do this. I have seen that most people are using https://github.com/chriskacerguis/codeigniter-restserver. Please guide me on writing a REST api only using CodeIgniter. Helpful links and steps are highly appreciated.

Thanks in Advance.

like image 357
Cyclops Avatar asked May 04 '16 13:05

Cyclops


People also ask

Can we write REST API in PHP?

REST API provides endpoints (URLs) that you call to perform CRUD operations with your database on the server. Previously, we have talked about How to build a REST API in Node. js and Flask. Today, we will learn how to set up a PHP server and write a small REST API using it.


1 Answers

If your are using version 3, you can do this

create a controller users.php

class Users extends CI_Controller {

    /**
    * @route http://proyect/users
    * @verb GET
    */
    public function get()
    {
        echo "Get";
    }

    /**
    * @route http://proyect/users
    * @verb POST
    */
    public function store()
    {
        echo "Add";
    }

    /**
    * @route http://proyect/users
    * @verb PUT
    */
    public function update()
    {
        echo "Update";
    }

    /**
    * @route http://proyect/users
    * @verb DELETE
    */
    public function delete()
    {
        echo "Delete";
    }

}

edit (add) in your application/config/route.php

$route["users"]["get"]    = "users/get";
$route["users"]["post"]   = "users/store";
$route["users"]["update"] = "users/update";
$route["users"]["delete"] = "users/delete";

$route['products/([a-zA-Z]+)/edit/(\d+)'] = function ($product_type, $id)
{
        return 'catalog/product_edit/' . strtolower($product_type) . '/' . $id;
};
like image 50
elddenmedio Avatar answered Oct 01 '22 18:10

elddenmedio