Данный класс содержит методы для работы с методами и параметрами REST API.
Объект SimpleRestRequest
Используйте метод sws.restRequestV1, как описано в примере ниже, чтобы создать объект SimpleRestRequest.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|
This server class allows to operate with the REST API methods and parameters.
SimpleRestRequest()
Initializes an empty SimpleRestRequest object. When using such an object, specify the method and the endpoint manually.
SimpleRestRequest(requestName, methodName)
This method is intended to create an object used in the REST requests. When using the method, an object is created with the sws prefix (see the code example below for clarification).
Parameter(s):
Name | Type | Mandatory | Default ValueNNNN
Info |
---|
Provide values for parameters as shown below Укажите значения параметров, как показано ниже: ParameterПараметр | ValueЗначение |
---|
requestName | Specify the value of the Name field taken from the record in the REST Requests Укажите значение поля Наименование из записи в таблице Запросы REST (sys_rest_requests) table. | methodName | Specify the value of the Name field taken from the record in the REST Request Methods Укажите значение поля Наименование из записи в таблице Методы REST (sys_rest_request_method)table related with this request, относящейся к этому запросу. |
|
ReturnВозвращаемое значение:
TypeDescriptionОписание |
---|
SimpleRestRequest object |
This method returns a SimpleRestRequest object initiated by the query transmitted; otherwise, it returns an empty SimpleRestRequest object. | Метод возвращает объект SimpleRestRequest, созданный при помощи переданного запроса. В случае ошибки метод возвращает пустой объект SimpleRestRequest. |
ПримерExample:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | SimpleRestRequestApiСоздание объекта SimpleRestRequest |
---|
linenumbers | true |
---|
|
/* CreateСоздайте theзапрос 'Telegram' в requestтаблице inЗапросы REST Requests (sys_rest_requestsrequest) table
andи theметод 'Send Message' в methodтаблице inМетоды REST Request Methods (sys_rest_request_method), tableсвязанной relatedс withзапросом 'Telegram' request.
AlsoТакже создайте createпараметры 'chat_id' andи 'text' в Restтаблице RequestПараметры Methodметодов ParamREST (sys_rest_request_method_param), связанные relatedс withметодом 'Send Message' method
*/
const request = sws.restRequestV1('Telegram', 'Send Message');
request.setStringParameter('chat_id', '123456789');
request.setStringParameter('text', 'telegram');
const response = request.execute();
// ORИЛИ
const request = sws.restRequestV1();
request.setRequestUrl('https://api.telegram.org/bot1860462740:AAHyP6BMH2Mh-cXezrTVu2sJUoNYvimMRMQ/sendMessage');
request.setQueryParameter('chat_id', '123456789');
request.setQueryParameter('text', 'telegram');
const response = request.execute(); |
addFileContent(
)content, paramName, fileName)
Используйте данный метод для подготовки файла в двоичном формате и его последующей отправки в запросе.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию | Описание |
---|
The method prepares a file in binary format for sending it in a request.
Parameter(s):
Name | Type | Mandatory | Default Value | Description |
---|
content | String | YДа | N | Нет | Данные двоичного файла в кодировке base64The base64 encoded binary file data. |
paramName | String | YДа | N | Нет | Название параметра в запросе POST, который передает двоичные данныеThe name of the parameter in the POST request that will transmit the binary data. |
fileName | String | YДа | N | Нет | Название файлаThe file name. |
Info |
---|
It is possible to add several files to one request. In this case, the name of the POST request parameter should look like an array of elements. For example, if there is one file, the parameter can be called files. If there are two files, they should be called files[1] and В один запрос можно добавить несколько файлов. В этом случае название параметра запроса POST должно представлять собой массив элементов. Например, если используется только один файл, параметр может называться files. Если используются два файла, их следует называть files[1] и files[2]. |
ReturnВозвращаемое значение:
TypeТип | DescriptionОписание |
---|
Void | This method does not return a valueМетод не возвращает значение. |
ExamplesПримеры:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | Adding two filesДобавление двух файлов |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestUrl('https://instance.example1.com/some/service'); //the URL from which the files are downloaded // URL откуда загрузить файлы
const downloadResponse = request.execute();
request.setRequestUrl('https://instance.example2.com/v1/attachments/upload/task/165469349718887155'); // the URL, onкуда which the files are uploadedзагрузить файлы
request.addFileContent(downloadResponse.getContentBase64(), 'files[1]', 'file.png');
request.addFileContent(downloadResponse.getContentBase64(), 'files[2]', 'file2.png');
const uploadResponse = request.execute(); |
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | Adding one fileДобавление одного файла |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestUrl('https://instance.example1.com/some/service'); //the URL fromоткуда which the file is downloadedзагрузить файл
const downloadResponse = request.execute();
request.setRequestUrl('https://instance.example2.com/v1/attachments/upload/task/165469349718887155'); // the URL, onкуда which the file is uploadedзагрузить файл
request.addFileContent(downloadResponse.getContentBase64(), 'files', 'file.mp3');
const uploadResponse = request.execute(); |
execute()
Sends the REST request.
Return:
Type | Description |
---|
SimpleRestResponse | This method returns a SimpleRestResponse object. |
Используйте данный метод для отправки запроса REST.
Возвращаемое значение:
ПримерExample:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | execute() |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestUrl(`https://jsonplaceholder.typicode.com/todos/1`);
request.setRequestMethod('GET');
const response = request.execute(); |
setBasicAuth(userName, userPassword)
Sets the username for the web service authentification if the basic authentication type was chosen.
Parameter(s):
Используйте этот метод, чтобы задать имя пользователя и пароль для авторизации в веб-службе, если выбран базовый тип авторизации.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|
Name | Type | Mandatory | Default ValueYNYNReturnВозвращаемое значение:
TypeDescriptionThis method does not return a valueМетод не возвращает значение. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | setBasicAuth() |
---|
linenumbers | true |
---|
|
const scriptJSON = {
'script': 'ss.info(new SimpleDateTime().getValue())'
}
const request = sws.restRequestV1();
request.setRequestUrl(ss.getProperty('simple.instance.uri') + '/v1/ajax-script/run');
request.setRequestMethod('POST');
request.setBasicAuth('admin', 'password');
request.setRequestHeader('Content-type', 'application/json');
request.setRequestBody(JSON.stringify(scriptJSON));
const response = request.execute();
ss.info(response.getBody());
// InfoИнформация: {"messages":[],"status":"OK","data":{"result":null,"info":"Info: 20... |
This code fragment below demonstrates how to retrieve the authorization token with a user login and password. The code uses example data for the the Фрагмент кода ниже демонстрирует, как получить токен авторизации с логином и паролем пользователя. В коде используются примеры данных для метода setRequestUrl(requestUrl) method and the и константы payload constant. Replace it with the real data before usage. Замените его реальными данными перед использованием.
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | Auth methodМетод авторизации |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestUrl('https://instance.example.com/v1/auth/login');
request.setRequestMethod('POST');
request.setRequestHeader('Content-type', 'application/json');
const payload = {
'username': 'admin',
'password': 'qwerty123456'
}
request.setRequestBody(JSON.stringify(payload));
const response = request.execute();
ss.info(JSON.parse(response.getBody()).data.auth_key); // InfoИнформация: 5WvOT9Ejlxd6Gb8bkCWMtG3XXMYcoDDJ |
setRequestUrl(requestUrl)
Используйте данный метод, чтобы задать URL-адрес запроса. Чтобы получить URL-адрес запроса, используйте метод getRequestUrl().
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|
Sets the request URL. To get a request URL, use the getRequestUrl() method.
Parameter(s):
Name | Type | Mandatory | Default ValueYNReturnВозвращаемое значение:
TypeDescriptionThis method does not return a valueМетод не возвращает значение. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | setRequestUrl() |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestUrl('https://instance.example.com/v1/ajax-script/run');
ss.info(request.getRequestUrl());
// InfoИнформация: https://instance.example.com/v1/ajax-script/run |
setRequestMethod(methodName)
Используйте данный метод, чтобы задать метод запроса Sets the requesting method (GET, POST, PURGE , etc). Specify the method name within the methodName parameter. To get the method name, use the getRequestMethod() method.
Parameter(s):
и пр.) Укажите название метода в параметреmethodName. Для того чтобы получить название метода, используйте метод getRequestMethod().
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|
Name | Type | Mandatory | Default ValueYNReturnВозвращаемое значение:
TypeDescriptionThis method does not return a valueМетод не возвращает значение. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | setRequestMethod() |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestUrl('https://instance.example.com/v1/ajax-script/run');
request.setRequestMethod('POST');
ss.info(request.getRequestUrl());
ss.info(request.getRequestMethod());
// InfoИнформация: https://instance.example.com/v1/ajax-script/run
// Info: POST |
setRequestTimeout(timeout)
Sets the response timeout (in seconds) until the request is out of time.
Parameter(s):
setRequestTimeout(timeout)
Используйте метод, чтобы устанавить время ожидания ответа запроса в секундах.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|
Name | Type | Mandatory | Default ValueY60ReturnВозвращаемое значение:
TypeDescriptionThis method does not return a valueМетод не возвращает значение. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | setRequestTimeout() |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestUrl('https://instance.example.com/v1/ajax-script/run');
request.setRequestMethod('GET');
request.setRequestTimeout(60);
const response = request.execute(); |
setQueryParameter(name, value)
Adds a parameter into the end of the request URL generated as Используйте этот метод, чтобы добавить параметр в конец URL запроса, сгенерированного как "name=value".
Parameter(s)Параметры:
NameTypeMandatory | Default ValueОбязательный | Значение по умолчанию |
---|
name | String |
YNYN ReturnВозвращаемое значение:
TypeDescriptionThis method does not return a valueМетод не возвращает значение. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | setQueryParameter() |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestUrl('https://instance.example.com/rest/v1/table/user');
request.setRequestMethod('GET');
request.setRequestHeader('Authorization', 'Bearer ' + new SimpleUser().getAccessToken());
request.setQueryParameter('sysparm_query', 'active=true^emailLIKEyours^ORDERBYDESCcompany');
const url = request.getRequestUrl();
ss.info(url);
// InfoИнформация: https://instance.example.com/rest/v1/table/user?sysparm_query=active%3Dtrue%5EemailLIKEyours%5EORDERBYDESCcompany |
setRequestBody(body)
Используйте этот метод, чтобы задать тело запроса при использовании методов PUT или POST. Чтобы получить тело запроса, используйте метод GET.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|
Sets the request body when the PUT or POST methods are used. To get the request body, use the GET method.
Parameter(s):
Name | Type | Mandatory | Default ValueYNReturnВозвращаемое значение:
TypeDescriptionThis method does not return a valueМетод не возвращает значение. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | setRequestBody() |
---|
linenumbers | true |
---|
|
const recordURL =
ss.getProperty('simple.instance.uri') + '/record/' + current.getTableName() + '/' + current.sys_id;
const dataJSON = {
'text': `New`Новый Requestзапрос hasназначен beenна assigned toкоманду DevOps Team <${recordURL}|View Request>`
};
const request = sws.restRequestV1('DevOps Team Request', 'send_message_to_channel');
request.setRequestBody(JSON.stringify(dataJSON));
const response = request.execute(); |
setStringParameter(name, value)
Sets the request variable with the name specified from the record to the value specified.
Parameter(s):
Используйте этот метод, чтобы установить переменную запроса с именем, указанным в name, в значение, указанное в value.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|
Name | Type | Mandatory | Default ValueYNYNReturnВозвращаемое значение:
TypeDescriptionThis method does not return a valueМетод не возвращает значение. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | setStringParameter() |
---|
linenumbers | true |
---|
|
/* CreateСоздайте theзапрос 'Telegram' в requestтаблице inЗапросы REST Requests (sys_rest_requestsrequest) table
andи theметод 'Send Message' в methodтаблице inМетоды REST Request Methods (sys_rest_request_method), tableсвязанной relatedс withзапросом 'Telegram' request.
AlsoТакже создайте createпараметры 'chat_id' andи 'text' в Restтаблице RequestПараметры Methodметодов ParamREST (sys_rest_request_method_param), связанные relatedс withметодом 'Send Message' method
*/
const request = sws.restRequestV1('Telegram', 'Send Message');
request.setStringParameter('chat_id', '123456789');
request.setStringParameter('text', 'telegram');
const response = request.execute(); |
name, value)
Используйте данный метод, чтобы установить заголовок HTTP в запросе с указанным значением. Чтобы получить заголовки запроса, используйте метод getRequestHeaders().
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|
Sets the HTTP header in the request with the value specified. To get request headers, use the getRequestHeaders() method.
Parameter(s):
Name | Type | Mandatory | Default ValueYNYNReturnВозвращаемое значение:
TypeDescriptionThis method does not return a valueМетод не возвращает значение. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | setRequestHeader() |
---|
linenumbers | true |
---|
|
const scriptJSON = {
'script': 'ss.info(new SimpleDateTime().getValue())'
}
const request = sws.restRequestV1();
request.setRequestUrl('https://instance.example.com/v1/ajax-script/run');
request.setRequestMethod('POST');
request.setBasicAuth('username', 'password');
request.setRequestBody(JSON.stringify(scriptJSON));
request.setRequestHeader('Content-type', 'application/json');
const response = request.execute(); |
getRequestUrl()
Используйте этот метод, чтобы получить URL-адрес запроса с параметрами. Чтобы установить URL-адрес запроса, используйте метод Displays the request URL with parameters. To set a request URL, use thesetRequestUrl(requestUrl) method.
ReturnВозвращаемое значение:
TypeDescriptionThe request URLМетод возвращает URL-адрес запроса. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | getRequestUrl() |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestUrl(ss.getProperty('simple.instance.uri') + '/v1/ajax-script/run');
const url = request.getRequestUrl();
ss.info(url);
// InfoИнформация: https://your-instance-url/v1/ajax-script/run |
getRequestBody()
Returns the request body. To set a request body, use the Используйте этот метод, чтобы получить тело запроса. Чтобы установить тело запроса, используйте метод setRequestBody(body) method.
ReturnВозвращаемое значение:
TypeDescriptionThe request bodyМетод возвращает тело запроса. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | getRequestBody() |
---|
linenumbers | true |
---|
|
const recordURL =
ss.getProperty('simple.instance.uri') + '/record/' + current.getTableName() + '/' + current.sys_id;
const dataJSON = {
'text': `New`Новый Requestзапрос has beenназначен assignedна toкоманду DevOps Team <${recordURL}|ViewПоказать Request>`запрос>`
};
const request = sws.restRequestV1('DevOps Team Request', 'send_message_to_channel');
request.setRequestBody(JSON.stringify(dataJSON));
request.execute();
const body = request.getRequestBody();
ss.info(body);
//InfoИнформация: {"text":"NewНовый Requestзапрос hasназначен beenна assigned toкоманду DevOps Team <https://your-instance-url.simpleone.ru\/record\/task\/161123123123123123|View Request>"} |
Используйте этот метод, чтобы получить все заголовки запроса. Чтобы установить заголовки запроса, используйте метод Returns all request headers. To set request headers, use the setRequestHeader(name, value) method.
ReturnВозвращаемое значение:
TypeDescriptionArray | The requested headers. |
Object | Метод возвращает объекты заголовков запроса. Ключи – это названия заголовков, а значения - массивы значений заголовков. |
ПримерExample:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | getRequestHeaders() |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestHeader('Content-type', 'application/json');
const header = request.getRequestHeaders();
ss.info(header);
// InfoИнформация: {"content-type":["application\/json"]} |
getRequestMethod()
Returns the request method. To set the request method, use the Используйте этот метод, чтобы вернуть метод запроса. Чтобы установить метод запроса, используйте setRequestMethod(methodName) method.
ReturnВозвращаемое значение:
TypeDescriptionThe method nameМетод возвращает название метода. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | getRequestMethod() |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestMethod('GET');
const method = request.getRequestMethod();
ss.info(method);
//InfoИнформация: GET |
useHttp2(value)
This method makes it obligaroty to use the Используйте этот метод, чтобы сделать протокол HTTP/2 protocolобязательным.
Note |
---|
Using this methods requires the host that also supports the При использовании этого метода необходимо, чтобы хост поддерживал протокол HTTP/2 protocol. |
Parameter(s)Параметры:
NameTypeMandatory | Default ValueОбязательный | Значение по умолчанию |
---|
value |
booleanN ReturnВозвращаемое значение:
TypeТип | DescriptionОписание |
---|
Void | This method does not return a valueМетод не возвращает значение. |
ExampleПример:
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | useHttp2() |
---|
linenumbers | true |
---|
|
const request = sws.restRequestV1();
request.setRequestUrl('https://http2.pro/api/v1');
request.setRequestMethod('GET');
request.useHttp2();
const response = request.execute(); |
To disable the usage of Чтобы отключить использование HTTP/2, you need to call the method passing the false parameter. , необходимо вызвать метод, передав параметр false.
Code Block |
---|
language | js |
---|
theme | Eclipse |
---|
title | useHttp2() |
---|
linenumbers | true |
---|
|
request.useHttp2(false); |