Exemple d’un squelette d’API REST avec Zend Framework.
Plugin d’authentification :
class RestAuth extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$apiKey = $request->getHeader('apikey');
if ($apiKey != 'secretKey') {
$this->getResponse()
->setHttpResponseCode(403)
->appendBody('Clef API invalide');
$request->setModuleName('default')
->setControllerName('error')
->setActionName('access')
->setDispatched(true);
}
}
}
Le controller principal qui va gérer l’utilisation de l’API pour les articles :
class ArticleController extends Zend_Rest_Controller
{
public function init()
{
$this->_helper->viewRenderer->setNoRender(true);
}
public function indexAction()
{
$this->getResponse()
->setHttpResponseCode(200)
->appendBody('Tous les articles');
}
public function getAction()
{
$this->getResponse()
->setHttpResponseCode(404)
->appendBody('Article n°5');
}
public function postAction()
{
$this->getResponse()
->setHttpResponseCode(201)
->appendBody('Article créé');
}
public function putAction()
{
$this->getResponse()
->setHttpResponseCode(503)
->appendBody('Article remplacé');
}
public function deleteAction()
{
$this->getResponse()
->setHttpResponseCode(204);
}
}