Building a REST API

Seotoaster plug-in system makes it easy to implement the REST API for  your plug-in. 

REST API defines a set of functions to which the developers can perform requests and receive responses via HTTP protocol. Because it uses HTTP, REST can be used practically for any programming language and easy to test. Read more here

Lets take a look on how to create a REST resource for our plugin. At first we will create a class, called Items to serve the todo items. At first lets create an Items.php in the Api/Todo directory

Selection_032

Now open this file and modify it to looks like example below

class Api_Todo_Items extends Api_Service_Abstract {

    protected $_accessList = array(
        Tools_Security_Acl::ROLE_SUPERADMIN => array(
            'allow' => array('get', 'post', 'put', 'delete')
        )
    );

    public function getAction() {
        // TODO: Implement getAction() method.    
    }

    public function postAction() {
        // TODO: Implement postAction() method.
    }

    public function putAction() {
        // TODO: Implement putAction() method.
    }

    public function deleteAction() {
        // TODO: Implement deleteAction() method.
    }
}

The class name should be Api_Todo_Items and should extend Api_Service_Abstract.

Api_Service_Abstract class - main Seotoaster API class which provides a set of useful methods to ensure a rapid development of the custom APIs. We recommend developers to investigate this class in details

Note: API reponse format is JSON
Note: Seotoaster API class also provides all the HTTP response codes (404, 500, etc...) as a constants. So, no need to prepare your own.

Request structure

Seotoaster REST API request structure is http://seotoasterhost/api/section/resource. In our case the section is represented by the folder in your plug-in’s Api directory (Todo) and the resource is represented by the class in the folder (Items.php). Finaly the request structure for our plugin will be http://seotoasterhost/api/todo/items

All API classes (resources) should implement four methods (actions): getAction, postAction, putAction, deleteAction. Seotoaster will lunch those actions via GET, POST, PUT and DELETE http requests respectively.


    // will  be lounched for teh GET request to te http://seotoasterhost/api/todo/items
    public function getAction() {
        ....
    }
    
    // will  be lounched for teh POST request to te http://seotoasterhost/api/todo/items
    public function postAction() {
        ....
    }

    // will  be lounched for teh PUT request to te http://seotoasterhost/api/todo/items
    public function putAction() {
          ....
    }

    // will  be lounched for teh DELETE request to te http://seotoasterhost/api/todo/items
    public function deleteAction() {
        ....
    }
}

API action access control

To restrict or allow acceess to specific API actions Seotoaster provides an array called $_accessList with the following structure

protected $_accessList = array(
    SEOTOSTER ROLE => array(
        'allow' => array('action', 'to', 'allow'),
        ‘deny’ => array(‘action’, ‘to’, ‘deny’)
    )
);

For example:

protected $_accessList = array(
    Tools_Security_Acl::ROLE_SUPERADMIN => array(
        'allow' => array('get', 'post', 'put', 'delete')
    )
);

API in action

Let’s see the REST API for our todo plugin in action. Modify your Items.php to looks like example below

/**
     * Todos mapper
     *
     * @var Todo_Models_Mapper_TodoMapper
     */
    protected $_mapper = null;

    protected $_accessList = array(
        Tools_Security_Acl::ROLE_GUEST => array(
            'allow' => array('get')
        ),
        Tools_Security_Acl::ROLE_SUPERADMIN => array(
            'allow' => array('get', 'post', 'put', 'delete')
        )
    );

    public function init() {
        $this->_mapper = Todo_Models_Mapper_TodoMapper::getInstance();
    }

    public function getAction() {
        $todos = $this->_mapper->fetchAll();
        return array_map(function($todo) {return $todo->toArray();}, $todos);
    }

Here we initialize a mapper to be able to fetch all our todo items from the database. In the getAction of our api we fetch all our todo items and make an array of them. And finally we return that array and it automatically transformed to JSON. Now open your browser and go to the http://www.seotoasterhost/api/todo/items/ you’ll see something like this

[
    {
        "text": "Explain plugin REST API",
        "status": "A",
        "id": 6
    },
    {
         "text": "This todo item is done",
         "status": "D",
         "id": 7
    },
    {
        "text": "Do some cool stuff with Seotoaster plugin",
        "status": "A",
        "id": 8
     }
]

And what about if we want to get a specific item via its id? Let’s see how we can do that
The request structure to get a specific item will be http://www.seotoasterhost/api/todo/items/id/6  and the modified get API action will looks like this

public function getAction() {
        $todoId = filter_var($this->_request->getParam('id'), FILTER_SANITIZE_NUMBER_INT);
        if($todoId) {
            $todo = $this->_mapper->find($todoId);
            if($todo instanceof Todo_Models_Model_Todo) {
                return $todo->toArray();
            }
            //todo item can not be found
            $this->_error('404 todo item can not be found!', self::REST_STATUS_NOT_FOUND);
        }
        $todos = $this->_mapper->fetchAll();
        return array_map(function($todo) {return $todo->toArray();}, $todos);
    }

Now open your browser and try to go to the http://www.seotoasterhost/api/todo/items/id/6 and you should see something like this as a result

{
    "text": "Explain plugin REST API",
    "status": "A",
    "id": 6
}

Nice and easy, huh?

For all the other actions

postAction - should controll the creation of the todo item

putAction - should control the update of the todo item

deleteAction - should control the delete of the todo item

You can find the full source code of those actions in the todo plugin surce code on GitHub

DevNews