Calling the REST API from a view¶
Polarion's REST API is the main way for a view to read and change data. The context gives you everything you need to call it: restBaseUrl and restToken.
REST API documentation
This page covers what is specific to calling the API from an application view. The API itself is documented in the Polarion REST API User Guide on the Siemens Xcelerator Developer Portal, and your server publishes its OpenAPI definition at https://<polarion-host>/polarion/rest/v1/definition.
A small helper¶
The examples that call the REST API use the same small helper, restFetch. Calls to your own endpoints go through its counterpart endpointFetch (see Call endpoints from a view). restFetch adds the token, sets the JSON headers, throws on HTTP errors and returns the parsed body:
import type { PolarionContext } from 'polarion-app-sdk';
/**
* Calls the Polarion REST API (JSON:API) on behalf of the logged-in user.
*
* `context.restBaseUrl` is the absolute base URL of the REST API, for example
* `https://host/polarion/rest/v1` (no trailing slash). `context.restToken` is a
* short-lived token that Polarion hands to the application view; it must be
* sent in the `X-Polarion-REST-Token` header.
*/
export async function restFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
const headers = new Headers(init.headers);
headers.set('X-Polarion-REST-Token', context.restToken ?? '');
headers.set('Accept', 'application/json');
if (init.body !== undefined && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json');
}
const response = await fetch(`${context.restBaseUrl}${path}`, { ...init, headers });
if (!response.ok) {
throw new Error(`REST ${response.status}: ${await response.text()}`);
}
if (response.status === 204) {
return null as T;
}
return (await response.json()) as T;
}
// WorkItemResponse and the other types live in src/types.ts of the examples.
const item = await restFetch<WorkItemResponse>(
context,
`/projects/${context.projectId}/workitems/${context.workItemId}?fields[workitems]=id,title,status`,
);
Authentication¶
Send the header on every request:
X-Polarion-REST-Token: <context.restToken>
The token represents the logged-in user. Calls fail with 401 if the token is missing, empty (token authentication not enabled on the server) or expired, and with 403 if the user lacks permission for the operation. On 401 after a long idle period, call fetchContext() again and retry once.
Do not send cookies or basic authentication; the token is sufficient and the recommended mechanism.
Reading a single resource¶
GET {restBaseUrl}/projects/test/workitems/TEST-514?fields[workitems]=id,title,status,type,description
{
"data": {
"type": "workitems",
"id": "test/TEST-514",
"attributes": {
"id": "TEST-514",
"title": "Brake pedal sensor",
"status": "open",
"type": "task",
"description": { "type": "text/html", "value": "<p>…</p>" }
},
"links": { "self": "…" }
}
}
Always ask for the fields you need with fields[<type>]=…. Without it the API returns a default set that omits most attributes; with @all it returns everything, which is slow for large items. Note that a sparse field set also filters relationships: to receive relationships.workItem on a link resource, workItem must be in fields[linkedworkitems].
Related resources: includes¶
Relationships are separate resources. To get the linked work items of an item together with their titles in one request:
GET {restBaseUrl}/projects/test/workitems/TEST-514/linkedworkitems
?fields[linkedworkitems]=role,suspect,workItem
&include=workItem
&fields[workitems]=id,title,status,type
The response has data (the link resources with a relationships.workItem.data.id) and included (the work items). Join them by id, as in the Work item card example.
Lists and queries¶
GET {restBaseUrl}/projects/test/workitems
?query=status:open AND type:task
&sort=-created
&fields[workitems]=id,title,status
&page[size]=100&page[number]=1
querytakes Polarion's Lucene query syntax, the same you type in the Work Items table.- Large page sizes may be capped by the server; the examples use
page[size]=100. Usepage[number]to walk further pages.meta.totalCountreports the total. sortaccepts a field name, prefixed with-for descending.
A selection of ids becomes one query: id:(TEST-514 TEST-513 TEST-511).
Writing¶
Updates use PATCH with a JSON:API document that repeats type and id:
await restFetch(context, `/projects/test/workitems/TEST-514`, {
method: 'PATCH',
body: JSON.stringify({
data: { type: 'workitems', id: 'test/TEST-514', attributes: { title: 'New title' } },
}),
});
Polarion answers with a 2xx status and no body on success (the examples expect 204 No Content). Creating resources uses POST on the collection URL with data as an array; deleting uses DELETE. Writes go through the same workflow and permission checks as the UI, so a field that is read-only for the user's role is also read-only through the API.
After a write, the Polarion form or table around your view does not know about the change. Tell the user to reload, or navigate with a target="_top" link; the host bridge has no "refresh" call yet.
Encoding¶
Use URLSearchParams for query strings. It encodes the brackets in fields[workitems] and the spaces in Lucene queries correctly:
const params = new URLSearchParams({
query: 'status:open AND type:task',
'fields[workitems]': 'id,title,status',
'page[size]': '100',
});
const url = `${context.restBaseUrl}/projects/${context.projectId}/workitems?${params}`;
Error handling¶
| Status | Meaning in a view | What to do |
|---|---|---|
| 400 | Bad request shape or unknown field | Fix the request; the body contains errors[].detail. |
| 401 | Missing or expired token | Check that token authentication is enabled; refetch the context. |
| 403 | User may not do this | Show a message; do not retry. |
| 404 | Wrong project/id, or no read permission | Verify ids from the context. |
| 409 | Concurrent modification or workflow conflict | Reload and let the user try again. |
The error body is JSON:API as well:
{ "errors": [ { "status": "403", "title": "Forbidden", "detail": "…" } ] }
Performance notes¶
- One request with
includebeats N requests for related items. - Keep
fields[…]tight;descriptionand other rich-text fields are large. - For aggregations over hundreds of items, a server script is usually faster than paging through the API from the browser.
More in Performance and load.