Message-ID: <1339851959.3752.1485855160805.JavaMail.confluence@ip-10-127-227-164> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_3751_1559313065.1485855160804" ------=_Part_3751_1559313065.1485855160804 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location: file:///C:/exported.html Using the JavaScript REST API Client

Using the JavaScript REST API Client

=20
=20
=20
=20

The JavaScript REST API Client is a JavaScript library meant to ease the= use of the eZ Platform REST API. For now, it can only be used in a web bro= wser.

Installation

In t= he PlatformUIAssetsBundle

Since the JavaScript REST Client is one of the foundations of the Platform Backend Interface, the client is provided by the PlatformUIA= ssetsBundle which is installed by default. As a result, the client is d= irectly available and can be embedded in any Platform-generated page with t= he following Twig code:

Embedding the JavaScript REST Client
=20
<script src=3D"{{ asset('bundles/ezplatformuiassets/vendors/ez-j=
s-rest-client/dist/CAPI.js') }}"></script>
<!-- or the minified version -->
<!-- <script src=3D"{{ asset('bundles/ezplatformuiassets/vendors/ez-j=
s-rest-client/dist/CAPI-min.js') }}"></script> -->
=20

With Bower

Alternatively, the JavaScript REST Client can be installed directly in a= ny project with Bower:

Installing with bower
=20
$ bower install --save ezsystems/ez-js-rest-client
=20

After using this command, dist/CAPI.js or dist/CAPI-m= in.js are available in bower\_components/ez-js-rest-client/.

Manual install

It is also possible to directly retrieve either dist/CAPI.js or dist/CAPI-min.js in the Github = repository of the project.

Usage examples

Once included, CAPI.js exports the eZ namespac= e which contains eZ.CAPI, the constructor function of the clie= nt. This constructor must receive the API end point and an authentication a= gent responsible for handling the authentication (session or basic auth). T= his is detailed in the Instantiation and authentication section below.

The auto-generated API documentation of the = JavaScript REST API client is available online. Like in the Public API,= the code is organized around 3 main services:

In essence, the operations available through those services are asynchro= nous, so all the corresponding methods accept a callback function as its la= st argument. This callback function will be called when the operation has b= een done and it will receive two arguments:

  1. error: depending on the success of the operation, this par= ameter is either false or a CAPIError instance representing the error=
  2. response: it's always of a Response instance allowing you to retri= eve any information from the REST API response

I= nstantiation and authentication

The eZ.CAPI c= onstructor function expects two parameters:

  1. the API end point URI
  2. an authentication agent instance to configure the client for the authentication mechanism c= onfiguration in eZ Platform.

The JavaScript REST Client comes with two authentication agents for the = Session and Basic Auth authentication mechanism.

Session auth

The Session Auth Agent expects an object describing the existing Session= or containing the credentials for the user to create the corresponding ses= sion. So if the user is not yet authenticated, the client can be instantiat= ed with:

Session Authentication (new session)
=20
var capi,
    credentials =3D {
        login: 'admin',
        password: 'publish',
    };

capi =3D new eZ.CAPI(
    'http://example.com',
    new eZ.SessionAuthAgent(credentials)
);
capi.logIn(function (error, response) {
    if ( error ) {
        console.log('Error!');
        return;
    }
    console.log("I'm logged in");
});
=20

Instead of passing the credentials to the eZ.SessionA= uthAgent constructor, it is also possible to pass this object as the first parameter= of the logIn method.

If the user already has a session, the agent expects an object describin= g the session, something like:

Session Authentication (existing session)
=20
var capi,
    sessionInfo =3D {
        name: 'eZSESSID', // name of the session, might also be something l=
ike eZSESSID98defd6ee70dfb1dea416cecdf391f58
        identifier: '6pp87ah63m44jdf53b35qlt2i7', // session id
        href: '/api/ezp/v2/user/sessions/6pp87ah63m44jdf53b35qlt2i7',
        csrfToken: 'memEneT7WvX9WmSlG2wDqUj0eeLRC7hXG--pLUx4dFE', // can be=
 retrieved with @security.csrf.token_manager Symfony service
    };

capi =3D new eZ.CAPI(
    'http://example.com',
    new eZ.SessionAuthAgent(sessionInfo)
);
capi.isLoggedIn(function (error, response) {
    if ( error ) {
        console.log('Error!');
        return;
    }
    console.log("I'm logged in");
});
=20

Basic auth

When configured in the Basic Authentication, the basic auth agent just e= xpects the user's credentials:

Basic Authentication
=20
var capi,
    credentials =3D {
        login: 'admin',
        password: 'publish',
    };

capi =3D new eZ.CAPI(
    'http://example.com',
    new eZ.HttpBasicAuthAgent(credentials)
);
capi.logIn(function (error, response) {
    if ( error ) {
        console.log('Error!');
        return;
    }
    console.log("The credentials are valid");
});
=20

Lo= ading a ContentInfo or a Content

To load a ContentInfo, you need the Content Service, it is returned by the getCon= tentService method on the client instance:

Loading a ContentInfo
=20
var capi, contentService,
    contentRestId =3D '/api/ezp/v2/content/objects/1',
    credentials =3D {
        login: 'admin',
        password: 'publish',
    };

capi =3D new eZ.CAPI(
    'http://example.com',
    new eZ.SessionAuthAgent(credentials)
);
contentService =3D capi.getContentService();
contentService.loadContentInfo(contentRestId, function (error, response) {
    if ( error ) {
        console.log('Error!');
        return;
    }
    // response.document contains the parsed JSON structure
    console.log('Content name: ' + response.document.Content.Name);
})
=20

If you run this example, you should see in the browser network panel a G= ET HTTP request to http://example.com/api/ezp/v2/= content/objects/1 with the necessary headers to get a JSON representati= on of the ContentInfo. If you want to load the Content instead, you can use= the loadContent method.

Moving a Locatio= n

To move a Location, the Content Service is also needed, this operation will generate a = MOVE HTTP request. If configured for the session authentication mechanism, = the client will automatically add the CSRF Token.

Moving a Location
=20
var capi, contentService,
    locationRestId =3D '/api/ezp/v2/content/locations/1/43/53', // Media/Mu=
ltimedia in a default install
    newParentLocationRestId =3D '/api/ezp/v2/content/locations/1/43/52', //=
 Media/Files in a default install
    credentials =3D {
        login: 'admin',
        password: 'publish',
    };

capi =3D new eZ.CAPI(
    'http://example.com',
    new eZ.SessionAuthAgent(credentials)
);
contentService =3D capi.getContentService();
contentService.moveSubtree(locationRestId, newParentLocationRestId, functio=
n (error, response) {
    if ( error ) {
        console.log('Error!');
        return;
    }
    console.log('Media/Multimedia is now Media/Files/Multimedia');
})
=20

Se= arching for Content or Location

Searching for Content or Location can be done with REST views= . REST views can be configured with the search en= gine criteria to match some Content items or Locations:

REST views
=20
var capi, contentService, query,
    credentials =3D {
        login: 'admin',
        password: 'publish',
    };

capi =3D new eZ.CAPI(
    'http://example.com',
    new eZ.SessionAuthAgent(credentials)
);
contentService =3D capi.getContentService();
query =3D contentService.newViewCreateStruct('test-rest-view', 'LocationQue=
ry'); // use 'ContentQuery' to retrieve a list of Content items
query.body.ViewInput.LocationQuery.Criteria =3D { // use 'ContentQuery' her=
e as well
    FullTextCriterion: "ez",
};
query.body.ViewInput.LocationQuery.limit =3D 10;
// query.body.ViewInput.LocationQuery.offset =3D 0;
contentService.createView(query, function (error, response) {
    if ( error ) {
        console.log('Error!');
        return;
    }
    console.log("Search results", response.document.View.Result.searchHits.=
searchHit);
})
=20

REST views

REST views are designed to be persisted but this feature is not yet impl= emented. As a result, when calling createView, the POST reques= t does not create the view but directly returns the results.

=20
=20
=20
=20

In this topic:

=20
=20
=20
------=_Part_3751_1559313065.1485855160804--