---
title: "Custom endpoints"
site: api
version: 1.11
versions: "all"
url: https://docs-new.servicely.ai/api/1.11/rest/custom-endpoints/
type: reference
application: platform_integration
last_updated: 2026-10-19
commit: f1879fd7e955
---


A system controller is a server script that Servicely runs when a request reaches `/controller/<name>`. Use one when an external system or a client script needs logic or a response shape that the table endpoints of the REST API do not give.

## How a controller works

Administrators create controllers under **Administration → Business Logic → Controller**. A controller has a **Name**, an **Active** flag, a **Description** and a **Script**.

<Image src="asset:screenshots/api/rest-custom-endpoints/image.png">A system controller named GreetingExampleController, with its one-line script that builds a greeting from the name parameter.</Image>

A request to `https://<instance>.servicely.ai/controller/<Name>` runs the active controller whose name matches exactly. Any HTTP method reaches it. The script runs as the authenticated user, so table access follows that user's permissions. It can call script libraries and every server scripting object, such as `Table`.

Callers authenticate as for the REST API: basic authentication, a bearer token, HMAC header validation or HMAC body validation. A request without valid authentication returns 401. To limit a System API token to one controller, set its **URL Allowed Paths** to `/controller/<Name>`.

Client scripts call a controller with `WS.controller("<Name>", data)`. See [UI events](page:admin/automation/ui-events) in the Administrator guide.

## Script variables

| Variable | Description |
| --- | --- |
| Each key of the payload | The JSON body's top-level keys become variables of the same name. With no body, the query parameters do. |
| `_data` | The whole JSON body, or the query parameters when there is no body. |
| `controller` | The controller object, which sets the status, headers and body of the response. |
| `current` | The form record, when a client script sends one. |
| `log` | The script logger, as in any server script. |

For this payload, `name` holds `"Example name"` and `relateddata.managerid` holds `"00000000000000000000000000000001"`.

```json
{
    "id": "00000000000000000000000000000010",
    "name": "Example name",
    "relateddata": {
        "managerid": "00000000000000000000000000000001"
    }
}
```

## Responses

By default the value of the script's last expression is returned under a `data` key, as JSON with status 200. Assigning the result to a variable named `answer` and ending with `answer;` is the usual pattern.

Calling `setBody` or `setJsonBody` on `controller` replaces that envelope. The response then holds only the body you set.

| Method | Returns | Description | Since |
| --- | --- | --- | --- |
| `setBody(body: string)` | `controller` | Sends the string as the body, unchanged. | 1.11 |
| `setJsonBody(obj: any)` | `controller` | Serialises the object to JSON and sends it as the whole body, with no `data` key. | 1.11 |
| `setContentType(contentType: string)` | `controller` | Sets the `Content-Type` header. The default is `application/json`. | 1.11 |
| `setStatus(code: number)` | `controller` | Sets the HTTP status code. The default is 200. | 1.11 |
| `setHeader(name: string, value: string)` | `controller` | Sets a response header. | 1.11 |

The methods return the controller object, so calls chain.

If the script throws an error, or no active controller has the name, the response is 500 with the message in `_error`.

```json
{
    "_error": "<error message>"
}
```

## Examples

### Return a greeting

The controller in the screenshot builds a greeting from the `name` key.

<CodeTabs>
  Servicely Script

  ```javascript
  answer = "Hello " + name + "!";
  ```
</CodeTabs>

<CodeTabs>
  Response

  ```json
  POST /controller/GreetingExampleController
  {"name": "Example name"}

  HTTP/1.1 200 OK
  {
      "data": "Hello Example name!"
  }
  ```
</CodeTabs>

### Answer a client script

This controller returns a user's location for a client script that sends `userId`.

```javascript
answer = {};

if (userId) {
    let userRec = Table("User", userId);
    if (userRec && userRec.Location.hasValue()) {
        answer.locationID = userRec.Location.value();
        answer.locationName = userRec.Location.displayValue();
    }
}

answer;
```

### Return custom JSON

<CodeTabs>
  Servicely Script

  ```javascript
  controller.setJsonBody({ hello: "world" });
  ```
</CodeTabs>

<CodeTabs>
  Response

  ```json
  {
      "hello": "world"
  }
  ```
</CodeTabs>

### Return XML

<CodeTabs>
  Servicely Script

  ```javascript
  controller
      .setContentType("application/xml")
      .setBody("<xml><status>created</status></xml>");
  ```
</CodeTabs>

<CodeTabs>
  Response

  ```http
  HTTP/1.1 200 OK
  Content-Type: application/xml

  <xml><status>created</status></xml>
  ```
</CodeTabs>

### Create an incident with error handling

This controller creates an incident from an external payload, maps the caller's classification to a Servicely one and reports failures with a status code. The classification IDs are sample data.

```javascript
/*
 * Payload: { "issueSummary": "Unresponsive database", "classification": "DB access" }
 */
const classificationMap = {
    "DB access": "00000000000000000000000000000100",
    "Server performance": "00000000000000000000000000000101"
};
const defaultClassification = "00000000000000000000000000000111";

if (!issueSummary) {
    controller.setStatus(400).setJsonBody({ message: "Issue summary not provided." });
} else {
    try {
        let newInc = Table("Incident")
            .newRecord()
            .Requestor(user.getID()) // The token's impersonated user
            .ShortDescription(issueSummary)
            .Classification(classificationMap[classification] || defaultClassification)
            .create();

        controller.setJsonBody({
            message: newInc.Number() + " created.",
            servicelyID: newInc.getID()
        });
    } catch (e) {
        log.error("Controller CreateIncident failed: " + e);
        controller.setStatus(500).setJsonBody({ message: "Incident not created: " + e });
    }
}
```

## Related

- [Quick start](page:rest/quick-start)
- [Sign requests with HMAC](page:rest/sign-requests-with-hmac)
- [Authentication methods for inbound integrations](page:admin/integrations/inbound-authentication)
- [Script libraries](page:admin/automation/script-libraries)
