eZ Community » Forums » Extensions » Rest API "Hello World"
expandshrink

Rest API "Hello World"

Rest API "Hello World"

Monday 07 February 2011 5:50:08 pm - 7 replies

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

<?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?

Modified on Monday 07 February 2011 6:01:49 pm by Thiago Campos Viana

Saturday 26 February 2011 1:24:53 pm

Same test using 4.5.0beta1 in Ubuntu, same error.

Modified on Saturday 26 February 2011 1:44:31 pm by Thiago Campos Viana

Saturday 26 February 2011 2:42:56 pm

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 blunk.gif Emoticon.

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

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

Saturday 18 June 2011 9: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>";
}
 
?>

Modified on Saturday 18 June 2011 10:10:21 pm by Thiago Campos Viana

Tuesday 12 July 2011 6:19:50 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 ?

Friday 15 July 2011 1:57:19 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 ?

Maybe standardization and oAuth, also check:

Why would one use REST instead of Web services?

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

Monday 18 July 2011 3:44:01 pm

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

Wednesday 22 August 2012 4:12:50 pm

Hi,

i tried your script but I receive the following error:

The Script only works, when I disable authentication. Any hints?

An error occured. These are the response headers from the REST service: 

 Array
(
    [0] => HTTP/1.1 500 Internal Server Error
    [1] => Date: Wed, 22 Aug 2012 14:09:20 GMT
    [2] => Server: Apache/2.2.14 (Ubuntu)
    [3] => X-Powered-By: eZ Publish
    [4] => Set-Cookie: eZSESSID=3osmgme57l5nak3me5ni231qg3; path=/
    [5] => Expires: Thu, 19 Nov 1981 08:52:00 GMT
    [6] => Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    [7] => Pragma: no-cache
    [8] => Set-Cookie: eZSESSID=nvhsm0pt3aevi2lcsnqbo6e2g0; path=/
    [9] => Content-Length: 697
    [10] => Connection: close
    [11] => Content-Type: application/json; charset=UTF-8
)

Edit: it works now. It was just some configuration error. Does anybody have an example where for the post request using the refresh_token when the access_token is expired?

Modified on Friday 14 September 2012 7:44:25 am by Andreas Adelsberger

expandshrink

You must be logged in to post messages in this topic!

36 542 Users on board!

Forums menu

Proudly Developed with from