🚀 Welcome to MDriven Learn –  MDriven is now on Discord!  Don’t miss the latest Release Notes.
Call Turnkey REST from Javascript
This page was created by Wikiadmin on 2026-07-29. Last edited by Wikiadmin on 2026-07-29.

You can call a REST-enabled ViewModel on MDriven Turnkey from JavaScript, whether your script runs in the Turnkey site or in an approved external web application.

Choose the connection pattern

Your browser's origin is the scheme, host, and port of the page running the JavaScript. For example, `http://localhost:62031` and `http://localhost:5052` are different origins because their ports differ.

Where the JavaScript runs What you must configure Typical authentication
On the same origin as Turnkey No cross-origin configuration is required. The user's existing Turnkey session cookie is sent with the request.
On another origin Configure CORS in the Turnkey model to allow that exact origin. Do not use a broad allow-all policy when requests use login credentials. Send the existing Turnkey session cookie with `withCredentials`, or use a JWT flow as described in Documentation:Connecting javascript SinglePageApplications to Turnkey (SPA).

Prerequisites in Turnkey

Before writing JavaScript, expose and secure the target ViewModel.

  1. In MDriven Designer, select the root of the ViewModel that JavaScript will call.
  2. Set the ViewModel tagged value RestAllowed to true.
  3. Add the appropriate access group. User-specific services commonly use the `IsLoggedIn` access group.
  4. If the ViewModel must read data for the signed-in user, include `SysSingleton.oclSingleton.CurrentUser` in the ViewModel and use it as the starting point for the user-specific data.
  5. Publish the model and verify the endpoint manually while signed in.

Turnkey checks both `RestAllowed` and the ViewModel access groups before returning data. For route formats, request parameters, supported verbs, and response behavior, see HowTos:Expose REST Service.

Example endpoint

A GET request identifies the ViewModel with the `command` parameter:

http://localhost:5052/TurnkeyRest/Get?command=ViewModel1

In this example, `ViewModel1` must have `RestAllowed` enabled. If it requires `IsLoggedIn`, the browser must already have a valid Turnkey login session.

Configure CORS for an external application

Cross-Origin Resource Sharing (CORS) is the browser security mechanism that determines whether JavaScript hosted on one origin may read a response from another origin. CORS is not needed when your page and Turnkey use the same origin.

For an external application, implement the CORS model pattern so that Turnkey approves only known application origins. The SPA pattern uses a `KnownExternalApp` object with an `Origin` and `IsOk` value. Its `GetAllowOriging` method can allow the request origin only when it is known and approved:

if KnownExternalApp.allinstances->exists(x|(x.Origin=org) and (x.IsOk)) then
  true
else
  false
endif

Create one approved `KnownExternalApp` entry for each origin that hosts your JavaScript. An origin must match the URL from which the browser loads the app; changing the protocol, host, or port creates a different origin.

Do not configure CORS to accept every origin when you rely on login cookies. Browsers do not permit credentialed cross-origin requests with an unrestricted origin policy.

For the complete CORS model pattern and an SPA example, see Documentation:Connecting javascript SinglePageApplications to Turnkey (SPA).

Use the existing Turnkey login session

A REST-enabled ViewModel with an `IsLoggedIn` access group requires a Turnkey login before the REST call. Choose a user journey that makes that login state clear:

  • Host or link to the external application from a Turnkey page, and show the link only to signed-in users.
  • Send the user from the external application to a Turnkey page to sign in, then provide a link back to the external application.
  • Expose a separate REST-enabled ViewModel without an access group that reports whether the user is signed in. Use that result to decide whether to direct the user to the Turnkey login page.

When calling from another origin, set `xhrFields: { withCredentials: true }`. This tells jQuery's XMLHttpRequest to send the user's existing session cookie. It does not log the user in; the user must already have a valid Turnkey session.

Call a ViewModel with jQuery

Place the following markup and script in the page that hosts your JavaScript. Replace the URL and `ViewModel1` with your Turnkey address and REST-enabled ViewModel name.

<div>
  <input type="button" value="Try it" onclick="sendRequest()" />
  <span id="value1">(Result)</span>
</div>

<script>
  const serviceUrl =
    'http://localhost:5052/TurnkeyRest/Get?command=ViewModel1';

  function sendRequest() {
    $.ajax({
      type: 'GET',
      url: serviceUrl,
      xhrFields: { withCredentials: true }
    })
    .done(function (data) {
      $('#value1').text(JSON.stringify(data));
    })
    .fail(function (jqXHR, textStatus) {
      $('#value1').text(jqXHR.responseText || textStatus);
    });
  }
</script>

Turnkey returns the ViewModel content as JSON. The example uses `JSON.stringify(data)` so that an object response can be displayed in the page. In application code, use the returned JSON fields rather than displaying the full response.

Send ViewModel variables

You can declare String variables in the target ViewModel and supply their values in the query string. For example, if `ViewModel1` declares `MyVar` and `MyOtherVar` as String variables:

http://localhost:5052/Rest/ViewModel1/Get/rootobjref?MyVar=hello&MyOtherVar=world

Turnkey assigns matching GET parameter names to the ViewModel variables. Use a complete root object ID when the ViewModel requires one; see HowTos:Expose REST Service for valid routes and ID requirements.

Diagnose failed requests

Symptom Meaning and next action
The browser reports only `error`, with no useful response body The browser may have blocked the response because of CORS. Confirm that the page origin is an approved origin in the Turnkey CORS model and that the request URL is correct.
Response says `AccessDenied` Turnkey found the ViewModel but its access groups denied the current request. Confirm `RestAllowed`, the ViewModel access groups, and that the user is logged in when `IsLoggedIn` is required.
A user-specific ViewModel returns no expected user data Confirm that `SysSingleton.oclSingleton.CurrentUser` is included in the ViewModel and that the request uses the intended signed-in session.
The request works on a Turnkey page but not from the external app The applications are probably on different origins. Configure CORS for the external app origin and retain `withCredentials: true` when reusing the Turnkey login session.

Use JWT authentication for a single-page application

A single-page application can obtain a JWT from an OAuth provider and send it in an `Authorization` header instead of depending on an existing Turnkey login page flow. Turnkey validates the token through `SysExternalJWTDefinition`; its `AcceptAndTransformUserName` method can accept, transform, or reject the token user name. When a nonempty user name is accepted, Turnkey looks up an existing `SysUser` and marks that user as logged in for subsequent requests.

The following request pattern sends an ID token to a Turnkey REST endpoint:

const headers = new Headers();
headers.append('Authorization', `Bearer ${response.idToken}`);

fetch('http://localhost:5052/TurnkeyRest/Get?command=RestExample', {
  method: 'GET',
  headers: headers
})
  .then(response => response.json())
  .then(data => console.log(data));

Configure the external application origin and audience validation as part of the JWT setup. Follow Documentation:Authenticate with a jwt and Documentation:Connecting javascript SinglePageApplications to Turnkey (SPA) for the required `SysExternalJWTDefinition`, OAuth keys, audience handling, and SPA configuration.

See also