Step 3: Extending the REST API
This example adds GET /api/myapi/v1/hello/:name, which answers {"greeting":"Hello, <name>"}, in the extension myapi.
1. The provider
<?php
// extension/myapi/classes/myapirestprovider.php
class myApiRestProvider implements ezpRestProviderInterface
{
public function getRoutes()
{
return array(
'myApiHello' => new ezpRestVersionedRoute(
new ezpMvcRailsRoute( '/hello/:name', 'myApiRestController', array( 'http-get' => 'hello' ) ), 1 ),
);
}
public function getViewController()
{
return new myApiRestViewController();
}
}
Route names must be unique across providers; prefix them with your extension's name.
2. The view controller
<?php
// extension/myapi/classes/myapirestviewcontroller.php
class myApiRestViewController implements ezpRestViewControllerInterface
{
public function loadView( ezcMvcRoutingInformation $routeInfo, ezcMvcRequest $request, ezcMvcResult $result )
{
return new ezpRestJsonView( $request, $result );
}
}
3. The controller
<?php
// extension/myapi/classes/myapirestcontroller.php
class myApiRestController extends ezpRestMvcController
{
public function doHello()
{
$result = new ezpRestMvcResult();
// route variables are properties of the controller
$result->variables = array( 'greeting' => 'Hello, ' . $this->name );
return $result;
}
}
To answer an error, set a status instead of variables: $result->status = new ezpRestStatusResponse( 404, array( 'error' => 'not_found' ) );. The call runs as the authenticated user, so check permissions as the content module does (for example with $node->canRead()) before you return content.
4. The settings
# extension/myapi/settings/rest.ini.append.php [ApiProvider] ProviderClass[myapi]=myApiRestProvider # optional: no answer cache for this controller [myApiRestController_CacheSettings] ApplicationCache=disabled
5. Activate and try
php bin/php/ezpgenerateautoloads.php -e php bin/php/ezcache.php --clear-tag=ini curl -s -H "Authorization: Bearer $EXP_API_KEY" https://www.example.com/api/myapi/v1/hello/world
Activate the extension first (Setup > Extensions), reload PHP-FPM, and restart Exponential Velocity if you use it.
A personal API key is limited to its scopes: a route that should accept keys needs a scope in rest.ini [ApiKeySettings] RouteScopes[<Controller>_<action>]; a GET or HEAD route without an entry needs DefaultReadScope, and any other route without an entry is refused for a key. See Personal API keys.
Next: Conclusion.
Contributors
- Geir Arne Waaler
- Graham Brookins Updated Maintainer
Comments
Add a comment