Zero Resource Model quick start tutorial

This tutorial provides a brief introduction to the Zero Resource Model and illustrates how quickly you can get up and running with RESTful data.
images/basic.png

See the video screencast of this tutorial and its accompanying transcript.

Before you begin

This tutorial assumes you have already installed the Command Line Interface (CLI) and are familiar with the basics of starting a new application and resolving dependencies. Also, the tutorial assumes use of the default embedded Derby database for persistence. Consult the full ZRM documentation for details on other supported databases and how to configure them.

Overview

In this tutorial you will see:

  • Database is automatically created from resource model definitions
  • Data fixtures are loaded into the database, by default
  • Quickly enable HTTP RESTful APIs with list, filter, retrieve, create, update, and delete operations

Uses of ZRM in this tutorial

With the 'M' in ZRM standing for Model, it should come as no surprise that the keystone of this tutorial is the Resource Model definition. The first part of the tutorial leads up to defining and synchronizing with the database whereas the rest of the tutorial illustrates what RESTful interactions can be performed once the declared model is synchronized.

Resource Model definitions

Resource Model definition is used for creating database artifacts for persistence and gives shape to HTTP representations. Further, provides metadata for ZRM's validation framework.

Resource Models are defined and declared in JSON files, one per resource in the app/models folder. By convention, the name of the JSON file names the resource. For example an persons resource would be named persons.json and might contain the following field definitions:

{
    "fields" : {
        "first_name": {"type":"string"},
        "birth_date": {"type":"date"},
        "is_child": {"type": "boolean"}
    }
}

The Model file name is significant and by convention names the Type of the Model. Thus, this Model is of Type persons. Instances of a Type are called Members and must conform to the constraints defined in the Type's Model. A group of Members is called a Collection.

Further, Resource Model Types are given additional properties by ZRM. The id field is autogenerated by default, but you can assign a value, as well. It must be an integer value. The updated field is a timestamp indicating the last time the Member instance was updated.

Loading initial data

The Zero Resource Model can load initial data into its database. This is done by specifying an initial_data.json file in the application's app/models/fixtures folder. Other data files located in this folder can be loaded by executing the model loaddata command line task.

These data files also have JSON contents but take on a slightly different shape than the Resource Model definitions. Each data file can have data for any number of Resource Model types and all are aggregated by a JSON array.

For instance, the following example contains two persons instances and one addresses instance:

[
    {
        "type": "persons",
        "fields": {
            "id": 301
            "first_name": "Bill",
            "age": 34,
            "is_child": false
        }
    },
    {
        "type": "addresses",
        "fields": {
            "id": 38
            "street": "100 Maple Ave",
            "city": "Anytown",
            "state": "NY"
        }
    },
    {
        "type": "persons",
        "fields": {
            "first_name": "Frank",
            "age": 28,
            "is_child": true
        }
    }
]

From this example, you can see that the model type order does not matter and the id field is optional. If you do not specify an id value, one will be autogenerated.

By default, any data in the initial_data.json will be loaded when you execute the model sync command line task. Other data files in the app/models/fixtures folder can be loaded by executing the model loaddata task as follows:

zero model loaddata another_file.json

Loading data can only be after the database is synchronized with the model type definitions. This is shown in the following section.

Synchronizing the database

The Zero Resource Model creates requisite database artifacts necessary to support the defined Resource Models by issuing the model sync command line task as follows:

zero model sync

Resetting the database

model reset is used during development when you make changes to existing models.

Because there is a level of ambiguity in tracking certain types of changes to model type declarations, model sync will not alter any database artifacts. It will only create newly added models. You will need to navigate and reconcile the differences on your own.

However, during development, when you make changes to model declarations after executing model sync, you may alternatively use model reset. Executing this CLI task will drop all database artifact, and run model sync. Thus all existing data will restored to the state at the last model sync.

zero model reset

Enabling the HTTP REST API

By default, your resources defined as Resource Models are not available over HTTP until you explicity indicate so by providing a hook into the resource framework. This is done by creating a resource script in the app/resources folder with the same name as the Resource Model defined in app/models.

The Zero Resource Model has a generic handler that responds to resource events (such as onList, onRetrieve, onCreate, onDelete, etc.). In order to route HTTP resource events into this default behavior, you must provide one delegating method call in the resource script in app/resources.

For instance, if you have an persons Resource Model defined in app/models/persons.json, then you create a file located at app/resources/persons.groovy with the following script:

ZRM.delegate()

That's it! with the Resource Model defined, data loaded, and the HTTP API enabled, you are ready to start accessing your data RESTfully.

Tutorial steps

Use the following steps:

  1. Create a new application by issuing the following CLI task from the command line anywhere on the file system:

    zero create zrmsample
    
  2. Change into your newly created, empty application:

    cd zrmsample
    
  3. Add a dependency on the zero.resource in the {app_root}/config/ivy.xml file of the application as shown in the following example:

    <dependency org="zero" name="zero.resource" rev="[1.0.0.0, 2.0.0.0["/>
    
  4. Resolve the dependency on zero.resource by issuing the following CLI task from the command line in the application's root:

    zero resolve
    
  5. Create the following new directories that are not created in the application template:

    models

    Create this directory under the app directory: {app_root}/app/models

    fixtures

    Create this directory under the newly created models directory: {app_root}/app/models/fixtures

  6. Create a resource model definition and data fixtures. Add a persons.json file to {app_root}/app/models with the following contents:

    {
        "fields" : {
            "first_name": {"type":"string"},
            "birth_date": {"type":"date"},
            "is_child": {"type": "boolean"}
        }
    }
    

    For more information, see the Resource Model declaration article.

  7. Add an initial_data.json file to {app_root}/app/models/fixtures with the following contents:

    [
        {
            "type": "persons",
            "fields": {
                    "first_name"    :   "Tommy",
                    "birth_date"    :   "2005-12-12",
                    "is_child"      :   "false"
            }
        },
        {
            "type": "persons",
            "fields": {
                    "id"            :   "2",
                    "first_name"    :   "Billy",
                    "birth_date"    :   "1983-04-10",
                    "is_child"      :   "true"
            }
        }
    ]
    

    Learn more about how ZRM automatically does database generation and loads initial data.

  8. Create the persons.groovy resource handler file in {app_root}/app/resources with the following code:

    ZRM.delegate()
    

    For more information about enabling HTTP REST access, see the Enabling HTTP access information.

  9. Run the model sync CLI task from your application's root:

    zero model sync
    
  10. Before starting the new application, make sure you stop any existing applications using the default port of 8080.

  11. Start the application:

    zero start
    
  12. If you make changes to your model during development, run model reset. This will change the database to reflect your changes, but also has the side affect of reverting all your data to the contents of your initial_data.json file:

    zero model reset
    
Because ZRM using embedded Derby as a convenience to quickly get started developing your RESTful applications, you must stop and start your application if you need to run model sync or model reset. This limitation imposed by Derby is not an issue when connecting to any of the other supported databases, including DB2, Oracle, MySQL, and network Derby.

Testing your application's data

  1. Point your browser to http://localhost:8080/resources/persons and confirm that an array JSON representation with the data in the initial_data.json file is returned.
  2. Point your browser to http://localhost:8080/resources/persons/100 and confirm that an object JSON representation is returned with id equals 100.
  3. Point your browser to http://localhost:8080/resources/persons?first_name__startswith=B and confirm that an object JSON representation is returned with id equals 2.

In addition to robust querying over HTTP, ZRM also provides RESTful create, update, and delete over HTTP. This tutorial does not go into details, however, you can learn more about reading and writing collection members.

When using the links above, your browser may ask you if you wish to save the file content. This is because the browser sees the content as MIME type application/json, which most browsers do not know how to display. The JSON data returned is just text, so you can set that MIME type to be always shown in your browser. You can also save the file and open it in a text editor.

It is also useful to have tools and browser plugins, like Poster, to interact with your RESTful services.

Building a front-end application with ZRM

When ZRM data services are enabled, you can rapidly build a front-end application in HTML using Dojo. Dojo is the preferred JavaScript framework for IBM&reg; WebSphere sMash applications and enables compelling user interfaces quite quickly. For the remainder of the tutorial, we will build a simple application.

Using the ZRM Dojo DataStore

The zero.dojo module provides components that enhance Dojo. One of its features is an implementation of the dojo.data API, zero.resource.DataStore, for ZRM-based applications. In building an example frontend application, we will use the zero.grid.DataGrid widget that can operate on the DataStore.

  1. Stop your application if it is currently running. Applications should be stopped before modifying their configuration.

  2. Add a dependency on the zero.dojo in the ivy.xml file of the application as shown in the following example:

    <dependency org="zero" name="zero.dojo" rev="[1.0.0.0, 2.0.0.0["/>
    
  3. Resolve the dependency on zero.dojo by issuing the following CLI task from the command line in the application's root:

    zero resolve
    
  4. Create the following an datagrid.html file in the public folder of your app and save the following contents into the file:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Using DataStore with the Dojo Grid</title>
    
        <script type="text/javascript"
            src="/dojo/dojo.js"
            djConfig="parseOnLoad: true"></script>
    
        <script type="text/javascript">
            dojo.require("dojo.parser");
            dojo.require("zero.resource.DataStore");
            dojo.require("zero.grid.DataGrid");
        </script>
    
        <style type="text/css">
            @import "/dijit/themes/soria/soria.css";
            @import "/dojo/resources/dojo.css";
            @import "/zero/grid/DataGrid/DataGrid.css";
            @import "/dojox/grid/_grid/Grid.css";
            @import "/dojox/grid/_grid/soriaGrid.css";
        </style>
    
    </head>
    
    <body class="soria">
    
        <!-- DataStore instance -->
        <div dojoType="zero.resource.DataStore" jsId="thestore"
             contextRoot=""
             resourceCollection="persons"></div>
    
        <!-- DataGrid instance -->
        <div dojoType="zero.grid.DataGrid" id="thegrid"
            store="thestore"
            style="width: 600px; height: 300px;"></div>
    
    </body>
    </html>
    
  5. Point your browser to http://localhost:8080/datagrid.html and experiment with your sample data. You can create new, modify existing, and delete rows. Further, if you click on column headers, it will sort the table.

This example shows that with just a bit of JavaScript, CSS, and declarative Dojo programming, you can quickly get a working application that populates data from the server and persists changes back to the server.

Version 1.1.0.0.21442