Call endpoints from a view¶
The context gives a view everything it needs to call the application's endpoints: appEndpoint (the base URL) and restToken (the authentication token). The rest is fetch().
Every GET and POST request must send a valid context.restToken in the X-Polarion-REST-Token header. The browser's Polarion session and cookies do not authenticate endpoint calls. If the token is empty, enable REST token authentication before calling endpoints.
The helper¶
import type { PolarionContext } from 'polarion-app-sdk';
/** Envelope that Polarion wraps around every server-script response. */
interface Envelope<T> {
timestamp?: string;
success?: boolean;
error?: string;
data?: T;
}
/**
* Calls one of the application's own endpoints declared in
* manifest.json under `serverScripts.endpoints`.
*
* `context.appEndpoint` is the absolute base URL of those endpoints, for example
* `https://host/polarion/apps/com.example.traceability/rest` (no trailing slash), so `path`
* starts with a slash, as in `restFetch`: `"/validate"`. The same
* `X-Polarion-REST-Token` header as for the REST API authenticates the call.
* The response envelope is unwrapped so callers only see the script's result.
*/
export async function endpointFetch<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.appEndpoint}${path}`, { ...init, headers });
// Script errors come back as HTTP 400 with the envelope, so parse the body
// whenever it is JSON and surface the script's own message.
const text = await response.text();
let envelope: Envelope<T> | undefined;
try {
envelope = JSON.parse(text) as Envelope<T>;
} catch {
envelope = undefined;
}
if (envelope && (envelope.success === false || envelope.error)) {
throw new Error(envelope.error ?? 'Server script reported an error.');
}
if (!response.ok || !envelope) {
throw new Error(`Endpoint ${response.status}: ${text}`);
}
return envelope.data as T;
}
The helper does four things: builds the URL from appEndpoint, sets the X-Polarion-REST-Token header, sets Content-Type: application/json when there is a body, and unwraps the envelope. Script errors arrive as HTTP 400 with the envelope, so the helper parses the body on every status and throws an Error with the script's own message when success is false.
endpointFetch is the counterpart of restFetch from Calling the REST API from a view: the same arguments, a path that starts with /, and the same token header. The examples keep both in src/polarion.ts under these two names.
GET with query parameters¶
import type { PolarionContext } from 'polarion-app-sdk';
import { endpointFetch } from './polarion';
interface LinkedTreeResult { item: TreeNode }
async function loadTree(context: PolarionContext) {
const params = new URLSearchParams({
objectId: `${context.projectId}/${context.workItemId}`, // required on every call
depth: '2',
});
return endpointFetch<LinkedTreeResult>(context, `/linked-tree?${params}`);
}
URLSearchParams encodes slashes and spaces correctly.
POST with a JSON body¶
interface ValidateResult {
results: { id: string; title: string; status: string; findings: { code: string; message: string }[] }[];
summary: { items: number; withFindings: number; byCode: Record<string, number> };
}
async function validate(context: PolarionContext, objectIds: string[]) {
return endpointFetch<ValidateResult>(context, '/validate', {
method: 'POST',
// objectId is required on every call; the body must be a flat object with
// string values, so the list is encoded as a JSON string.
body: JSON.stringify({ objectId: objectIds[0], objectIds: JSON.stringify(objectIds) }),
});
}
Polarion parses the POST body as a flat object of string parameters. A nested array or object is rejected with HTTP 500 (Expected a string but was BEGIN_ARRAY) before the script runs. Encode structured input as a JSON string and parse it in the script with JSON.parse(arguments.getAsString('objectIds')).
Types for your contract¶
Declare the request and response shapes once in src/types.ts and use them in both the helper calls and the components. Because view and endpoint ship together, the TypeScript types are the documentation of the contract; keep them next to the script that implements it.
Handling the outcome¶
try {
const result = await validate(context, ids);
setResults(result.results);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
Three kinds of failure reach the catch:
| Failure | Message |
|---|---|
| HTTP error before the script ran (unknown endpoint, missing token, bad content type, non-string body value) | Endpoint 404: …, Endpoint 401: …, Endpoint 400: …, Endpoint 500: {"error":"… Expected a string but was BEGIN_ARRAY …"} |
The script returned { error } or threw (HTTP 400 with the envelope) | the script's message, for example validate failed: Error: objectIds: expected "PROJECT/WI-ID", got "DP-461" |
| Network problem | the browser's fetch error |
Show the message; for 401, call fetchContext() again to refresh the token and retry once.
Loading state and cancellation¶
Endpoint calls can take longer than REST reads because they do more work. Show a loading state ("Computing the link tree on the server…") and, in views that react to selection changes, debounce calls and ignore stale responses:
useEffect(() => {
let cancelled = false;
const timer = setTimeout(() => {
validate(context, ids).then((r) => { if (!cancelled) setResults(r.results); });
}, 200);
return () => { cancelled = true; clearTimeout(timer); };
}, [context, ids]);
Calling endpoints from outside a view¶
Other clients must also send a valid REST token in the X-Polarion-REST-Token header. Session cookies and personal access tokens sent as Authorization: Bearer are not substitutes. Do not assume that an authentication method accepted by the standard REST API is accepted by application endpoints. See Test and debug for an HTTP client example.