JavaScript

Samples of usage of Targetprocess REST API in JavaScript code

Read data to the same domain (in Mashups)

Using jQuery:

$
    .getJSON('https://Targetprocess/api/v1/UserStories?include=[Id,Name]&take=1000')
    .then(function(data) {
        console.log('Response:', data.Items);
    });

$
    .ajax({url: 'https://Targetprocess/api/v1/UserStories?include=[Id,Name]&take=1000'})
    .then(function(data) {
        console.log('Response XML:', data);
    });

The same as a mashup with all necessary boilerplate:

tau.mashups
    .addDependency('jQuery')
    .addDependency('app.path')
    .addMashup(function($, appPath, config) {
        var apiRoot = appPath.get() + '/api/v1';

        $
            .getJSON(apiRoot + '/UserStories/?include=[Id,Name]&take=1000')
            .then(function(data) {
                console.log('Response:', data.Items);
                // do something with retrieved data
            })
            .fail(function(error) {
                console.log('Error:', error);
                // handle error somehow
            });
    });

❗️

Cross-origin web browser requests are denied in Targetprocess.

AJAX requests to Targetprocess' API data in third-party browser code could be done only in a mashups that are executed in the same origin as Targetprocess.

With attempt to run such requests in other websites you will receive multiple errors:

Solution
Use JSONP calls instead as described below.

Read data to different domains: Basic authentication

Here is an example of HTML page that contains embedded JavaScript code with AJAX call to Targetprocess REST API. In order to support cross-origin resource sharing (CORS) and allow to access Targetprocess data on different domains this example includes JSONP callback.

The example uses access credentials of the user who is logged in within web browser. Basic authentication method is used.

🚧

Allow Basic authentication for JSONP requests in Targetprocess Security settings

In Targetprocess System settings > Security settings Administrator can allow or disable Basic authentication for JSONP requests.

Token-based authentication is always allowed.

<!DOCTYPE html>
<html>
<head>
  <title>Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
</body>
<script>
function displayStories(data) {
  var $body = $("body");
  for (var i = 0; i <= data.Items.length; i++) {
    $body.append(data.Items[i].Name).append("<br>");
  }
}

$.getJSON("https://accountname.tpondemand.com/api/v1/userstories?format=json&callback=?", displayStories);
</script>
</html>

Next example also uses Basic authentication, but it allows to define login and password of any active Targetprocess user and use them for further access.

🚧

Pass login:password pair within application path

Do not use method setRequestHeader('Authorization', 'login', 'password') for your AJAX call because such headers are not included into such JSONP requests. Source

var applicationPath = 'https://login:[email protected]';
var userStoriesDatePath = applicationPath + '/api/v1/userstories?format=json';

$.ajax({
    type: 'GET',
    url: userStoriesDatePath,
    dataType: 'jsonp',
    success: function(data) {
        console.log('Success', data);
    },
    error: function(request, textStatus, errorThrown) {
        console.log('Error', request.responseText, textStatus, errorThrown);
    }
});

When the login:password pair provided in this script code cannot be verified by the server, the user will see popup dialog window requesting to input credentials to the web browser. These credentials will be used for authentication further.

❗️

Internet Explorer does not support JSONP with Basic authentication

Injection of credentials to URL is not supported in IE web browser. Use token-based authentication method in IE instead of Basic one.

Read data to different domains: Token authentication

This example of JSONP AJAX GET request to Targetprocess REST API uses token-based authentication method.

var hostname = 'https://myaccount.tpondemand.com';
var authenticationToken = 'MTpFQUVXMHdRVGRMN0x1OXJPYWRXZWZaRkc2aDJaSkRyVWdyWm9rK2tFcldBPS==';
var isTokenSetFromUserProfileTab = true;
//use 'true' if token is issued from User Profile > Access Tokens tab
//use 'false' when token is issued from /api/v1/Authentication API endpoint
  
var takeCount = 10;
var entityTypeResourceName = 'userstories';
var filter = '';
var includeFields = '';

var dataUrl = hostname + '/api/v1/' + entityTypeResourceName + '?format=json' +
    '&where=' + filter +
    '&take=' + takeCount +
    (includeFields.length > 0 ? '&include=' + includeFields : '') +
    '&' + (isTokenSetFromUserProfileTab ? 'access_token' : 'token') + '=' + authenticationToken;

$.ajax({
    type: 'GET',
    url: dataUrl,
    dataType: 'jsonp',
    success: function(data) {
        console.log('Success', data);
    },
    error: function(request, textStatus, errorThrown) {
        console.log('Error', request.responseText, textStatus, errorThrown);
    }
});

Modify data from the same domain (in Mashups)

This is an example of basic Mashup for Targetprocess. It creates a new user story in the account where it is installed. It uses token-based authentication method. When new story is created, its numeric ID is written into web browser console.

tau.mashups
.addDependency('jQuery')
.addDependency('app.path')
.addMashup(function($, appPath, config) {

  var authenticationToken = 'MTpFQUVXMHdRVGRMN0x1OXJPYWRXZWZaRkc2aDJaSkRyVWdyWm9rK2tFcldBPS==';
  var isTokenSetFromUserProfileTab = true;
  //use 'true' if token is issued from User Profile > Access Tokens tab
  //use 'false' when token is issued from /api/v1/Authentication API endpoint

  var entityTypeResourceName = 'userstories';
  var resultIncludeFields = '[Id,Name,CreateDate]';

  var dataUrl = appPath.get() + '/api/v1/' + entityTypeResourceName + '?format=json' 
  + '&resultInclude=' + resultIncludeFields
  + '&' + (isTokenSetFromUserProfileTab ? 'access_token' : 'token') + '=' + authenticationToken;

   $.ajax({
    type: 'POST',
    url: dataUrl,
    contentType: 'application/json',
    dataType: 'json',
    data: '{"Project" : {"ID" : 2}, "Name": "Test User Story Name", "Description": "Test User Story Description"}',
    success: function(data) {
      console.log(data);
    },
    error: function(request, textStatus, errorThrown) {
      console.log(request.responseText);
      console.log(textStatus);
      console.log(errorThrown);
    }
    });
});

Modify data from different domains

❗️

Cross-origin web browser requests are denied in Targetprocess

AJAX requests to Targetprocess' API data in third-party browser code could be done only in a mashups that are executed in the same origin as Targetprocess.

With attempt to run such requests in other websites you will receive multiple errors:

Multiple solutions are possible, all of them are either complex and require to configure some additional services or not secure:

  • Make POST requests to Targetprocess REST API from your backend side. Let your web browser post AJAX calls to your backend. Add proxy / forwarding scripts or services to your backend that will communicate with Targetprocess REST API and send results back to the web browser.
  • Disable Same Origin Policy in the settings of your web browser. Learn how.

Then you'll be able to post AJAX calls in the same form they are made from the same domain.

//this script works in a web browser only with Same Origin Policy disabled

var hostname = 'https://myaccount.tpondemand.com';
var authenticationToken = 'MTpFQUVXMHdRVGRMN0x1OXJPYWRXZWZaRkc2aDJaSkRyVWdyWm9rK2tFcldBPS==';
var isTokenSetFromUserProfileTab = true;
//use 'true' if token is issued from User Profile > Access Tokens tab
//use 'false' when token is issued from /api/v1/Authentication API endpoint
  
var entityTypeResourceName = 'userstories';
var resultIncludeFields = '[Id,Name,Description,CreateDate]';

var dataUrl = hostname + '/api/v1/' + entityTypeResourceName + '?format=json' 
+ '&resultInclude=' + resultIncludeFields
+ '&' + (isTokenSetFromUserProfileTab ? 'access_token' : 'token') + '=' + authenticationToken;

 $.ajax({
    type: 'POST',
    url: dataUrl,
    contentType: 'application/json',
    dataType: 'json',
		data: '{"Project" : {"ID" : 2}, "Name": "User Story Name", "Description": "User Story Description"}',
		success: function (data) {
			console.log(data);
		},
		error: function (request, textStatus, errorThrown) {
			console.log(request.responseText);
			console.log(textStatus);
			console.log(errorThrown);
		}
   });