E
E
Eugene Vdovenko2015-06-25 16:24:05
Zend Framework
Eugene Vdovenko, 2015-06-25 16:24:05

REST API for non-collection entity?

Understanding Apigility. Let's say I want the REST GET request api.site/version to return the API version.
In fact, we have Entity and Collection. Which of these should return version information? Maybe someone saw the thread implementation, dig for an example?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
snow_wons, 2015-09-10
@Misanthropist

To do this, you need to use not REST, but RPC service.
If done via HAL, then like this:

namespace Api\V1\Rpc\Version;

use Zend\Mvc\Controller\AbstractActionController;
use ZF\ContentNegotiation\ViewModel;

class VersionController extends AbstractActionController
{
    public function versionAction()
    {
        $hal = $this->getPluginManager()->get('hal');
        
        $o = $hal->createEntityFromMetadata(
            new Entity(), 
            $hal->getMetadataMap()->get('Api\\V1\\Rpc\\Version\\Entity')
        );
                
        return new ViewModel(array(
            'payload' => $o
        ));
    }
}

namespace Api\V1\Rpc\Version;

class Entity
{
    public $version = 1;
}

And in the module config
'zf-hal' => array(
        'metadata_map' => array(
            'Api\\V1\\Rpc\\Version\\Entity' => array(
                'route_name' => 'api.rpc.version',
                'entity_identifier_name' => 'version',
                'route_identifier_name' => 'version_id',
                'hydrator' => 'Zend\\Stdlib\\Hydrator\\ObjectProperty',
            ),

If HAL is not needed and a simple answer is enough:
namespace Api\V1\Rpc\Version;

use Zend\Mvc\Controller\AbstractActionController;

class VersionController extends AbstractActionController
{
    public function versionAction()
    {
        return ['version'=>1];
    }
}

Entity and code in the config is not needed.
But if you suddenly really want to use REST, then there is also a way.
namespace Api\V1\Rest\Version;

use ZF\Rest;

class VersionController extends Rest\RestController {

    protected function getIdentifier($routeMatch, $request)
    {
        return 'version';
    }

}

namespace Api\V1\Rest\Version;

class Entity
{
    public $version = 1;
}

namespace Api\V1\Rest\Version;

use ZF\Rest\AbstractResourceListener;

class VersionResource extends AbstractResourceListener
{
    public function fetch($id)
    {
         return new Entity();
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question