Rest API "Hello World"

Author Message

Thiago Campos Viana

Monday 07 February 2011 8:50:08 am

Hello everybody

I'm testing rest API, but can't use it, here's what I've been done.

  • Installed ez publish on windows, the url of the site was http://localhost/ez.
  • Changed my settings to force virtual host and removed the siteaccess if default siteaccess.
  • I activated all three extensions and executed the two sql scripts.
  • Created a copy of the index_rest.php to the root folder.
  • Changed the .htaccess:
Options -Indexes

DirectoryIndex index.php

RewriteEngine On

#Clustered setup switch
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/var/([^/]+/)?storage/images(-versioned)?/.*  /index_image-common.php [L]
        
RewriteCond %{HTTP_HOST} ^webdav\..*
RewriteRule ^(.*) webdav.php [L]

RewriteCond %{HTTP_HOST} ^soap\..*
RewriteRule ^(.*) soap.php [L]

RewriteRule ^api index_rest.php [L]
Rewriterule ^/var/static/.* - [L]
RewriteRule ^(.*)favicon\.ico - [L]
RewriteRule ^robots\.txt - [L]
RewriteRule ^sitemap\.xml - [L]
RewriteRule ^var/cache/debug.html.* - [L]
RewriteRule ^var/[^/]+/cache/debug.html.* - [L]
Rewriterule ^var/storage/.* - [L]
Rewriterule ^var/[^/]+/storage/.* - [L]
RewriteRule ^var/cache/texttoimage/.* - [L]
RewriteRule ^var/[^/]+/cache/texttoimage/.* - [L]
RewriteRule ^var/([^/]+/)?cache/public/.* - [L]
Rewriterule ^design/[^/]+/(stylesheets|images|javascript|flash)/.* - [L]
Rewriterule ^share/icons/.* - [L]
Rewriterule ^extension/[^/]+/design/[^/]+/(stylesheets|flash|images|lib|javascripts?)/.* - [L]
Rewriterule ^packages/styles/.+/(stylesheets|images|javascript)/[^/]+/.* - [L]
RewriteRule ^packages/styles/.+/thumbnail/.* - [L]
# Uncomment the following lines when using popup style debug.
# RewriteRule ^var/cache/debug\.html.* - [L]
# RewriteRule ^var/[^/]+/cache/debug\.html.* - [L]
RewriteRule .* index.php [L]

php_value magic_quotes_gpc "Off"
  • Registered the oauth application at oauthadmin/list as:
Name:

Test

Description:

test

Client identifier:

0483e65e220dc2e32bd2cea2b90e068b

Client secret:

d475d071de75ebe648e546e46b8e3653

Endpoint URI:

http://localhost/rpg/ezpRestDemo.php

  • Then I created the file http://localhost/rpg/ezpRestDemo.php:
<?php
/**
* This file is a demonstration of the eZ PUblish REST API developer preview. It handles oAuth2
* authorization, and will return as-is the JSON content returned by the REST interface.
*
* It doesn't cover the whole thing, but almost, and should give you all you need to get started
* with it !
*
* It accepts a few URL parameters that just change which REST resource is used:
* - resource: the REST resource URI that should be queried: content/node/2,
*   content/object/1/field/title, etc
*   Default: content/node/2
* - output: either json to get raw json, or html to get a preformatted print_r (default)
*
* Setup:
* - place this script in a folder on some web server. The only constraint is that it should be
*   able to access your eZ Publish (the one that has REST installed) over HTTP
* - in your eZ Publish backoffice, go to oauthadmin/list. Create a new application. Enter any
*   name (it doesn't matter), and enter the URL where you placed this script (the whole thing,
*   from http to .php).
* - on the details view for your newly created app (it should be oauthadmin/view/1), you will
*   see a "client_id", an md5 sum. Set this value as $appClientId below. It is  used to identify
*   the application requesting access.
* - set $eZHost below to your eZ Publish host (front or backoffice, doesn't matter)
* - open this script in your browser, WITHOUT parameters, and follow the leader.
*   The first time you authenticate, you will be asked if you want to authorize this application.
*   Once this is done, you can add parameters, as documented above:
*   - output=json will send you direct json. You can find browser plugins in order to view these
*     directly.
*   - resource must be given the REST resource you want to query. A few you can try until the
*     full doc is released:
*     - resource=content/node/<id>
*     - resource=content/node/<id>/fields
*     - resource=content/node/<id>/field/<attribute_identifier>
*/

 // or this would remove all the variables in the session, but not the session itself 
 
 session_start();

$resource = isset( $_GET['resource'] ) ? $_GET['resource'] : 'content/node/2';
$output = isset( $_GET['output'] ) ? $_GET['output'] : 'html';

// Of course need to customize these
$eZHost = 'http://localhost/ez';
$appClientId = '0483e65e220dc2e32bd2cea2b90e068b';

$ouAuthorize = "{$eZHost}/oauth/authorize";
$ouToken = "{$eZHost}/oauth/token";
$restUrl = "{$eZHost}/api/{$resource}";

if ( isset( $_GET['access_token'] ) )
{
    $_SESSION['token'] = $_GET['access_token'];
}
// we need a token to use the REST interface
elseif ( !isset( $_SESSION['token'] ) )
{
    $authParameters = array();
    $authParameters['redirect_uri'] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $authParameters['client_id'] = $appClientId;
    $authParameters['response_type'] = 'token';
    array_walk( $authParameters, function( &$value, $key ) {
        $value = "{$key}=" . urlencode( $value );
    });
    $uri = $ouAuthorize . '?' . implode( '&', $authParameters );

    // This will redirect the browser to the authorization page on eZ Publish itself
    header( "Location: $uri" );
    exit;
}

// Create a stream context with the Authorization header required by oauth based security
$streamOptions = array(
    'http' => array(
        'method' => 'GET',
        'header' => "Authorization: OAuth {$_SESSION['token']}",
    )
);
$context = stream_context_create( $streamOptions );

$result = @file_get_contents( $restUrl, false, $context );
if ( $result === false )
{
    echo "An error occured. These are the response headers from the REST service:\n<br />";
    echo "<pre>";
    print_r( $http_response_header );
    echo "</pre>";
    exit( 1 );
}
if ( $output == 'json' )
{
    header('Content-Type: application/json' );
    echo $result;
}
else
{
    echo "<pre>" . print_r( json_decode( $result ), true ) . "</pre>";
}
?>

The application redirects to the oauth page, I complete the login and I'm redirected back to the page, but I get a 404 error from ez publish.

Here's the php 5.3.1 module list:

Core, bcmath, calendar, com_dotnet, ctype, date, ereg, filter, ftp, hash, iconv, json, mysqlnd, odbc, openssl, pcre, Reflection, session, SPL, standard, tokenizer, zlib, libxml, dom, bz2, SimpleXML, wddx, xml, xmlreader, xmlwriter, xsl, apache2handler, Phar, curl, mbstring, exif, fileinfo, gd, gettext, imap, mcrypt, mysql, mysqli, PDO, pdo_mysql, PDO_ODBC, pdo_sqlite, soap, sockets, SQLite, sqlite3, xmlrpc, zip, ming, pdf, mhash, xdebug

I don't know what I'm doing wrong, could somebody help me?

eZ Publish Certified Developer: http://auth.ez.no/certification/verify/376924

Twitter: http://twitter.com/tcv_br

Thiago Campos Viana

Saturday 26 February 2011 4:24:53 am

Same test using 4.5.0beta1 in Ubuntu, same error.

eZ Publish Certified Developer: http://auth.ez.no/certification/verify/376924

Twitter: http://twitter.com/tcv_br

Jérôme Vieilledent

Saturday 26 February 2011 5:42:56 am

Hi Thiago

This is a known issue for 4.5.0beta1 : http://issues.ez.no/17951 .

It has been fixed and will be available for beta2, but anyway, the best way to workaround this would be to setup your test inside a VirtualHost, with eZ Publish directory as DocumentRoot ;-).

And by the way, do not forget to add this RewriteRule (before the one with index.php) :

RewriteRule ^/api/ /index_rest\.php [L]

Thiago Campos Viana

Saturday 18 June 2011 12:59:58 pm

Changed my demo code and now it works, forget my .htaccess file, just rename default .htaccess_root to .htaccess and change your settings/override/site.ini.append.php [SiteAccessSettings]ForceVirtualHost=true, the steps are the same, you'll just need to change the code I posted to:

<?php
/**
* This file is a demonstration of the eZ PUblish REST API developer preview. It handles oAuth2
* authorization, and will return as-is the JSON content returned by the REST interface.
*
* It doesn't cover the whole thing, but almost, and should give you all you need to get started
* with it !
*
* It accepts a few URL parameters that just change which REST resource is used:
* - resource: the REST resource URI that should be queried: content/node/2,
*   content/object/1/field/title, etc
*   Default: content/node/2
* - output: either json to get raw json, or html to get a preformatted print_r (default)
*
* Setup:
* - place this script in a folder on some web server. The only constraint is that it should be
*   able to access your eZ Publish (the one that has REST installed) over HTTP
* - in your eZ Publish backoffice, go to oauthadmin/list. Create a new application. Enter any
*   name (it doesn't matter), and enter the URL where you placed this script (the whole thing,
*   from http to .php).
* - on the details view for your newly created app (it should be oauthadmin/view/1), you will
*   see a "client_id", an md5 sum. Set this value as $appClientId below. It is  used to identify
*   the application requesting access.
* - set $eZHost below to your eZ Publish host (front or backoffice, doesn't matter)
* - open this script in your browser, WITHOUT parameters, and follow the leader.
*   The first time you authenticate, you will be asked if you want to authorize this application.
*   Once this is done, you can add parameters, as documented above:
*   - output=json will send you direct json. You can find browser plugins in order to view these
*     directly.
*   - resource must be given the REST resource you want to query. A few you can try until the
*     full doc is released:
*     - resource=content/node/<id>
*     - resource=content/node/<id>/fields
*     - resource=content/node/<id>/field/<attribute_identifier>
*/
 
 // or this would remove all the variables in the session, but not the session itself 
 session_start();

 
$resource = isset( $_GET['resource'] ) ? $_GET['resource'] : 'ezp/content/node/2';
$output = isset( $_GET['output'] ) ? $_GET['output'] : 'html';
 
// Of course need to customize these
$eZHost = 'http://localhost/ez_site';
$appClientId = 'your_client_identifier ';
 
$ouAuthorize = "{$eZHost}/oauth/authorize";
$ouToken = "{$eZHost}/oauth/token";
$restUrl = "{$eZHost}/api/{$resource}";
 
if ( isset( $_GET['access_token'] ) )
{
    $_SESSION['token'] = $_GET['access_token'];
}
// we need a token to use the REST interface
elseif ( !isset( $_SESSION['token'] ) )
{
    $authParameters = array();
    $authParameters['redirect_uri'] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $authParameters['client_id'] = $appClientId;
    $authParameters['response_type'] = 'token';
    array_walk( $authParameters, function( &$value, $key ) {
        $value = "{$key}=" . urlencode( $value );
    });
    $uri = $ouAuthorize . '?' . implode( '&', $authParameters );
 
    // This will redirect the browser to the authorization page on eZ Publish itself
    header( "Location: $uri" );
    exit;
}
 
// Create a stream context with the Authorization header required by oauth based security
$streamOptions = array(
    'http' => array(
        'method' => 'GET',
        'header' => "Authorization: OAuth {$_SESSION['token']}",
    )
);
$context = stream_context_create( $streamOptions );
 
$result = @file_get_contents( $restUrl, false, $context );
if ( $result === false )
{
    echo "An error occured. These are the response headers from the REST service:\n<br />";
    echo "<pre>";
    print_r( $http_response_header );
    echo "</pre>";
    exit( 1 );
}
if ( $output == 'json' )
{
    header('Content-Type: application/json' );
    echo $result;
}
else
{
    echo "<pre>" . print_r( json_decode( $result ), true ) . "</pre>";
}

?>

eZ Publish Certified Developer: http://auth.ez.no/certification/verify/376924

Twitter: http://twitter.com/tcv_br

H-Works Agency

Tuesday 12 July 2011 9:19:50 am

Hello everyone,

This rest api implementation in ezpublish looks great.

What are the benefit of using this technique to access ezpublish ressources instead of using a simple module view to return datas ?

EZP is Great

Thiago Campos Viana

Thursday 14 July 2011 4:57:19 pm

"

Hello everyone,

This rest api implementation in ezpublish looks great.

What are the benefit of using this technique to access ezpublish ressources instead of using a simple module view to return datas ?

"

Maybe standardization and oAuth, also check:

Why would one use REST instead of Web services?

Maybe Jérôme or Bertrand could enlighten us...

eZ Publish Certified Developer: http://auth.ez.no/certification/verify/376924

Twitter: http://twitter.com/tcv_br

Gaetano Giunta

Monday 18 July 2011 6:44:01 am

I'd also say oauth is the main difference today. That, and less memory / cpu consumption, as it uses a dedicated controller file (but I never tested for real the differences).

Pros of using ezjscore/ggwebservices stuff: better integration with the roles and policies system (but you have to set up custom authorization methods), usage of different protocols if your communication partner needs them (eg. a service can be exposed both as soap, rest and xmlrpc)

Pros of using json/xml in templates (eg layout/set/json/node/view/json/2): better integration with the roles and policies system (but you have to set up custom authorization methods), can benefit of the caching layer that is offered by the templating system

Pros of using custom modules/views: none really that I can think of at this stage, except you might be familiar with creating them

Principal Consultant International Business
Member of the Community Project Board

Powered by eZ Publish™ CMS Open Source Web Content Management. Copyright © 1999-2014 eZ Systems AS (except where otherwise noted). All rights reserved.