Developing REST ApplicationsArticle Link |
![]() |
This guide develops a small browser editor against the CDO Graph REST API and explains the application patterns that make edits safe. It covers discovery, graph reads, authentication, atomic commits, optimistic concurrency, and recovery after an uncertain commit result. The examples use CDO's Company model and its configured REST server.
For the endpoint and JSON schema reference, see REST API. For the service architecture, see REST Architecture. For server setup, see Configuring REST Services.
From the examples root, start the configured server with mvn -pl configured-server -Prest exec:exec, then open http://127.0.0.1:8081/company/. The application is served on the same origin as the REST API, mounted at /cdo/api/cdo/v1. The company URL alias selects the repo1 repository.
Table of Contents
| 1 | Getting Started | ||
| 2 | Reading Object Graphs | ||
| 3 | Committing Changes | ||
| 4 | Authentication and Permissions | ||
| 5 | Building a Web Editor | ||
| 6 | The Company Example and Further Reading | ||
Start with GET /cdo/api/cdo/v1/. The discovery document identifies the service name, preferred API version, supported versions, and capabilities. Then call GET /cdo/api/cdo/v1/repositories to list the repository aliases available to the caller. A repository entry includes its alias, repository name, and auditing and branching flags. Use the alias in subsequent URLs; the Company example uses company, which routes to repository repo1.
GET http://127.0.0.1:8081/cdo/api/cdo/v1/repositories
{"repositories":[{"name":"company","repository":"repo1","auditing":false,"branching":false}]}
The Company page and API share an origin, so the example can use relative Fetch URLs without a CORS preflight. When hosting a separate client, configure the REST service's CORS policy for that exact client origin. Do not put credentials in a query parameter or URL. Use GET /cdo/api/cdo/v1/repositories/company/resources?path=%2Fcompany to read the example resource.
A graph response contains a root reference, snapshot description, object table, and truncation flag. Objects use opaque IDs and logical types; references point to IDs in the object table. A representative response is:
{
"$root": {"$ref": "..."},
"$snapshot": {"branch": "MAIN", "timestamp": 0},
"$objects": [{
"$id": "...",
"$type": {"package": "http://www.eclipse.org/emf/CDO/examples/company/1.0.0", "name": "Company"},
"$features": {"name": "Example Company", "categories": [{"$ref": "..."}]},
"$meta": {"version": 3, "permission": "WRITE"}
}, {
"$id": "...",
"$type": {"package": "http://www.eclipse.org/emf/CDO/examples/company/1.0.0", "name": "Category"},
"$features": {"name": "Hardware", "products": [{"$ref": "..."}]}
}, {
"$id": "...",
"$type": {"package": "http://www.eclipse.org/emf/CDO/examples/company/1.0.0", "name": "Product"},
"$features": {"name": "Keyboard", "price": 49.95, "vat": "vat15"}
}],
"$truncated": false
}
Resolve each $ref through a map keyed by $id; do not assume object-table order or use object IDs as
durable application identifiers. Request metadata=version,permission when the client needs version
preconditions and permission-aware controls. Other supported metadata includes branch, created, revised, resource,
container, containerFeature, and permission.
The graph endpoint accepts branch, timestamp, depth, referenceDepth, collectionLimit, offset, metadata, and features. Use collectionLimit with offset to page large collections. A true $truncated value means the client must not present the graph as complete. Historical timestamps require auditing; branch selection requires branching support. The snapshot identifies the state that was read, while per-object versions are the preconditions for later writes. For example, ?path=%2Fcompany&depth=4&referenceDepth=1&collectionLimit=50&offset=0&features=name,categories,products selects a bounded projection. A projection may omit fields that an editor needs; only edit and submit features that were loaded. Containment depth follows resource and model containment; reference depth follows non-containment references and can expose connected objects without making them children of the root.
Submit a single JSON request to POST /repositories/{alias}/commits. Its operation list is one atomic repository commit. New objects use temporary IDs local to that request; create operations specify the logical type and resource or containment location, and later operations in the same list can refer to those IDs. For example, create a Company resource and its first Category in one batch:
{
"operations": [
{"op":"create", "id":"tmp:resource",
"type":{"package":"http://www.eclipse.org/emf/CDO/Eresource/4.0.0","name":"CDOResource"},
"container":"$root", "feature":"contents"},
{"op":"set", "object":"tmp:resource", "feature":"name", "value":"company"},
{"op":"create", "id":"tmp:company",
"type":{"package":"http://www.eclipse.org/emf/CDO/examples/company/1.0.0","name":"Company"},
"resource":"tmp:resource"},
{"op":"set", "object":"tmp:company", "feature":"name", "value":"Example Company"},
{"op":"create", "id":"tmp:category",
"type":{"package":"http://www.eclipse.org/emf/CDO/examples/company/1.0.0","name":"Category"},
"container":"tmp:company", "feature":"categories"},
{"op":"set", "object":"tmp:category", "feature":"name", "value":"Hardware"}
]
}
Persistent objects changed by set, unset, add, remove, move, or
detach need their versions in expectedVersions. A containment change also changes its persistent
owner: creating a child requires the existing owner's version, and removing or moving a child requires the owner's
version as well as that of the affected persistent object. Detaching a containment object cascades through its
containment subtree, so include the versions of every persistent object in that subtree. Temporary objects have
no server version and must not appear in the precondition map. A stale precondition rejects the whole batch with
HTTP 409; no partial operation list is applied. The response includes the commit branch and timestamp, temporary
to persistent idMappings, and resulting revisions.
Updating a persistent Product uses the version from the baseline graph. When adding a child to an existing Category, include the Category version because its containment feature changes:
{
"expectedVersions": {"product-id": 7, "category-id": 4},
"operations": [
{"op":"set", "object":"product-id", "feature":"price", "value":59.95},
{"op":"create", "id":"tmp:headset",
"type":{"package":"http://www.eclipse.org/emf/CDO/examples/company/1.0.0","name":"Product"},
"container":"category-id", "feature":"products"},
{"op":"set", "object":"tmp:headset", "feature":"name", "value":"Headset"},
{"op":"set", "object":"tmp:headset", "feature":"price", "value":79.95},
{"op":"set", "object":"tmp:headset", "feature":"vat", "value":"vat15"},
{"op":"detach", "object":"another-product-id"}
]
}
The example removes a Product by detaching it. Include that Product's version and the version of its Category
containment owner in the precondition map. After success, use the result's idMappings to relate each
temporary ID to its assigned ID, then reload the graph to establish fresh versions. On HTTP 409, keep local edits,
tell the user that another commit changed an affected revision, and offer an explicit reload or discard.
A network failure or server error after submitting the request can leave its result unknown. Never resend that batch: it may already have committed. Reload the affected resource and reconcile from the authoritative graph.
When the server has an authenticator configured, send its bearer token in the Authorization header:
const response = await fetch(url, {
headers: { Accept: "application/json", Authorization: `Bearer ${token}` }
});
Keep the token in memory for the active page session. Do not put it in a URL, activity log, persistent browser
storage, or diagnostic output. A 401 means authentication did not succeed; a 403 means the authenticated caller
lacks permission. Treat permission metadata as a hint for the interface, not as authorization: the server checks
every read and commit. A graph may omit inaccessible features or objects. Display only fields that were actually
returned, and avoid interpreting an omitted field as a writable empty value.
A caller with only partial read access might receive an object such as
{"$id":"...", "$type":{"package":"...","name":"Product"}, "$features":{"name":"Keyboard"}, "$meta":{"permission":"READ"}}.
Do not fill omitted price or VAT values with defaults and later submit them as if the caller had read the stored
values. If an endpoint returns 404 with the REST service's unknown-resource code, that is a missing
resource; 401 and 403 are authentication and authorization outcomes, not evidence that the resource is missing.
The editor requests version and permission metadata and disables controls unless the loaded object reports WRITE. New objects are editable locally because they do not have server permission metadata yet. A newly created child also requires write permission on its existing containment owner. The commit remains subject to server-side authorization even when the editor enables a control.
A robust editor keeps three related values: the current local graph, the last successfully loaded baseline, and the connection context that produced that baseline. The context includes service URL, repository alias, resource path, and authentication identity. Only compare or commit edits when the current settings still match the loaded context; changing the token or resource means the existing graph is no longer evidence about the selected target. Keep a version with each persistent object. Build operations by comparing local state with the baseline, and send expected versions only for changed persistent objects and affected containment owners. New local objects receive temporary commit IDs and no version precondition.
Serialize load, commit, and reload actions. While an action is active, show a busy state and disable duplicate submissions and conflicting edits. On a conflict, preserve the user's edits and explain that the stored object has changed; allow a deliberate reload or discard. Do not silently retry or merge a conflicting batch.
After a commit request loses its response, enter a recovery state that prevents another commit and blocks changes to the affected service, repository, resource, and credentials. Only a successful reload of that same context clears the state. If the commit response succeeds but the subsequent refresh fails, apply the same safeguard: the write is known to have succeeded, but the client has not established a new baseline. A failed reload never clears recovery. This rule prevents duplicate writes and keeps subsequent edits tied to a known graph.
The Company editor's local state follows this simple shape:
const state = {
graph: null, // Current values, including unsaved edits
baseline: null, // Last graph loaded successfully from the server
loadedContext: null, // Service, repository, resource, and token identity
dirty: false,
busy: false,
recovery: null // Set until the affected context reloads successfully
};
To prepare a write, compare each persistent object's current features with its baseline copy. Assign a
tmp:... ID to each newly created local object, then emit its create operation before operations that
populate it. Add the baseline version for each changed persistent object, each persistent containment owner
changed by the operation, and each persistent member of a detached containment subtree. Do not send versions for
temporary objects or unrelated unchanged objects. This is why the editor constructs the operation list from the
current graph and the original baseline together.
The activity log records method, URL, request body, status, duration, and response. Its request helper never records the bearer token or authorization header. It also bounds the in-memory log so a long editing session does not grow the page indefinitely.
The editor serializes the operation list and its preconditions in one request. After a successful response it reads the authoritative graph again; the ID map is useful to correlate newly created objects, but the refreshed graph supplies the next baseline and versions:
const { operations, expectedVersions } = createCommitOperations(state.graph, state.baseline);
try {
const result = await request(context, "POST", `${repositoryURL(context)}/commits`, {
expectedVersions,
operations
});
const assignedIDs = result.idMappings || {};
state.recovery = { context, message: "Reload before editing again." };
const graph = await readGraph(context, false);
applyLoadedGraph(context, graph);
} catch (error) {
if (error.status === undefined || error.status >= 500) {
requireRecovery(context, "Commit outcome is unknown. Reload; do not retry.");
}
}
A production handler also distinguishes a 409 conflict and other definite client errors so it can preserve local
edits and explain the response. A lost response or server failure after submission is different: keep the recovery
lock, do not resend the operation list, and clear the lock only after a successful reload of the same context.
Use textContent for model values and errors, and construct DOM nodes instead of interpolating user data into HTML. Keep request activity useful but bounded, and never record the authorization header or token. The Company example uses plain HTML, CSS, and readable JavaScript with no client framework or package installation.
Open the Company page, add a Category and Products, and inspect its REST Activity Log. Save the same repository in two tabs. Commit an edit in the first tab, then submit an edit to the same persistent object from the second. Its stale version should produce a conflict while preserving the second tab's local edits. Reload that tab to inspect the committed state. This demonstrates optimistic concurrency without a special test server.
The native RemoteClient in the same configured example connects to the same repository and resource, so it can inspect browser-created data using the ordinary CDO API. The canonical static assets are under web/company. REST request handling is implemented by RestDispatcher; commit operations are applied by RevisionGraphWriter. Both are under plugins/org.eclipse.emf.cdo.server.rest/src. The configured server example is under releng/org.eclipse.emf.cdo.releng/central/examples/configured-server; the editor assets are in web/company. Its JavaScript uses Fetch and the DOM directly, so it can be adapted by changing the model type and package URI, feature rendering, graph traversal, and operation builder while retaining the baseline, context, permission, and recovery rules.