HTTP
Methods of HTTP, GetRequest, HttpRequestWithBody, HttpResponse and HttpResponseBinary for sending HTTP requests from server scripts.
HTTP sends HTTP requests from server scripts, such as triggers, script libraries, jobs and system controllers, to other systems. It is a global object: call a method such as HTTP.get(url) to get a request, configure it, then call execute() to get a response.
Get an instance
let response = HTTP.get("https://example.com/api/items")
.queryString("status", "open")
.apiTokenAuth("Example outbound token")
.execute();
Every request carries User-Agent: servicely-http/1.0.0. GET, HEAD, POST, PUT and DELETE requests also send Accept: application/json, and POST, PUT and DELETE send Content-Type: application/json until you set another.
HTTP methods
| Method | Returns | Description | Since |
|---|---|---|---|
get(url: string) |
GetRequest | Creates a GET request. | 1.11 |
head(url: string) |
GetRequest | Creates a HEAD request. | 1.11 |
options(url: string) |
GetRequest | Creates an OPTIONS request, without the default Accept header. |
1.11 |
post(url: string) |
HttpRequestWithBody | Creates a POST request. | 1.11 |
put(url: string) |
HttpRequestWithBody | Creates a PUT request. | 1.11 |
patch(url: string) |
HttpRequestWithBody | Creates a PATCH request, without the default Accept and Content-Type headers. |
1.11 |
delete(url: string) |
HttpRequestWithBody | Creates a DELETE request. | 1.11 |
disableSSLValidation() |
HTTP | Skips certificate validation for the next request created, for example for a self-signed certificate. Works only when the application property system.http.client.disable.ssl.validation.allowed is true. Otherwise Servicely logs a warning and validates as usual. |
1.11 |
Request methods
GetRequest and HttpRequestWithBody share these methods. Each returns the request, so calls chain.
| Method | Returns | Description | Since |
|---|---|---|---|
apiTokenAuth(token: string) |
request | Signs the request with the System API Outbound Token of this name or key when it runs. | 1.11 |
basicAuth(username: string, password: string) |
request | Sets basic authentication credentials. Deprecated: use apiTokenAuth with a Basic outbound token. |
1.11 |
header(name: string, value: string) |
request | Sets a request header. | 1.11 |
headers(headers: object) |
request | Sets several headers from an object of names and values. | 1.11 |
queryString(name: string, value: string) |
request | Adds a query string parameter. | 1.11 |
queryString(parameters: object) |
request | Adds several query string parameters. | 1.11 |
routeParam(name: string, value: string) |
request | Replaces the {name} placeholder in the URL with the value. |
1.11 |
connectTimeout(ms: number) |
request | Sets the connection timeout in milliseconds. | 1.11 |
socketTimeout(ms: number) |
request | Sets the socket timeout in milliseconds. | 1.11 |
getUrl() |
string | Returns the request URL. | 1.11 |
execute() |
HttpResponse | Sends the request and returns the response with a text body. | 1.11 |
executeBinary() |
HttpResponseBinary | Sends the request and returns the response with a byte body. | 1.11 |
Body methods
HttpRequestWithBody adds these methods.
| Method | Returns | Description | Since |
|---|---|---|---|
contentType(type: string) |
request | Sets the Content-Type header. |
1.11 |
accept(type: string) |
request | Sets the Accept header. |
1.11 |
body(body: string) |
request | Sets the body to the string. | 1.11 |
bodyJson(body: any) |
request | Serialises the object to JSON and sets it as the body. | 1.11 |
bodyBytes(body: bytes) |
request | Sets the body to a byte array. | 1.11 |
field(name: string, value: string) |
request | Adds a multipart form field. | 1.11 |
fieldAttachmentById(name: string, attachmentId: string) |
request | Adds the attachment with this ID as a multipart file field. Call it once per file to send several. | 1.11 |
Response methods
HttpResponse and HttpResponseBinary share these methods. Each getter also has a short form without get, for example status() for getStatus().
| Method | Returns | Description | Since |
|---|---|---|---|
isError() |
boolean | True when the status is not 2xx. | 1.11 |
getStatus() |
number | The status code, or 0 when the request failed before a response arrived. | 1.11 |
getStatusText() |
string | The status text, or the error message when the request failed. | 1.11 |
getHeaders() |
object | The response headers. A repeated header keeps its first value. Names are case-sensitive in this object. | 1.11 |
getHeader(name: string) |
string | The first value of a header, matched without regard to case, or null. | 1.11 |
getHeaderValues(name: string) |
array | Every value of a header, in the order sent. | 1.11 |
HttpResponse adds the body methods.
| Method | Returns | Description | Since |
|---|---|---|---|
getBody() |
string | The body, or null. | 1.11 |
getJsonBody() |
any | The body parsed as JSON, or null when empty. Throws an error when the body is not JSON. | 1.11 |
HttpResponseBinary adds the attachment methods.
| Method | Returns | Description | Since |
|---|---|---|---|
toAttachment() |
TableRecord | Saves the body as an Attachment record and returns it. | 1.11 |
toAttachment(options: object) |
TableRecord | As toAttachment(), with field values for the new record. |
1.11 |
Examples
Handle errors
execute() does not throw on a network failure or an error status. Check isError() before you read the body. Servicely also logs each failed request.
Servicely Script
let response = HTTP.post("https://example.com/api/tickets")
.bodyJson({ summary: current.ShortDescription() })
.apiTokenAuth("Example outbound token")
.execute();
if (response.isError()) {
log.error("Ticket not sent: " + response.status() + " " + response.statusText());
} else {
let ticket = response.getJsonBody();
current.ThirdPartyReference(ticket.id);
}
Response
// response.status() -> 201
// response.isError() -> false
// response.getJsonBody() -> { id: "<external id>" }
Route parameters
HTTP.get("https://example.com/{resource}")
.routeParam("resource", "items")
.queryString("name", "example")
.execute();
// Sends GET https://example.com/items?name=example
Self-signed certificates
let body = HTTP.disableSSLValidation()
.get("https://example.com")
.execute()
.getBody();
Save a download as an attachment
toAttachment(options) takes RelatedField, ParentRecord, ExternalKey, FileName and MimeType. FileName defaults to the name in the Content-Disposition header and MimeType to the Content-Type header. The upload is validated like any attachment, and a rejected file throws an error. When the application property system.upload.permitted is false, the method returns null.
let url = "https://example.com/files/report.pdf";
HTTP.get(url).executeBinary().toAttachment({
RelatedField: "Attachments",
ParentRecord: current,
ExternalKey: url,
FileName: "report.pdf"
});