Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

 Используйте этот класс для работы с методами и параметрами REST API.


SimpleRestRequest(requestName, methodName)


Этот метод предназначен для создания объекта, используемого в запросах REST. При использовании метода создается объект с префиксом sws (см. пояснение в примере кода ниже).


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
requestNameStringНетНет
methodNameStringНетНет


Info

 Укажите значения параметров, как показано ниже:

ПараметрЗначение
requestName Укажите значение поля Наименование из записи в таблице Запросы REST (sys_rest_requests).
methodName Укажите значение поля Наименование из записи в таблице Методы REST (sys_rest_request_method), относящейся к этому запросу.


Возвращаемое значение:

ТипОписание
SimpleRestRequest objectЭтот метод возвращает объект SimpleRestRequest, созданный при помощи переданного запроса. В случае ошибки метод возвращает пустой объект SimpleRestRequest.


Пример:

Code Block
languagejs
themeEclipse
titleSimpleRestRequestApi
linenumberstrue
/* 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();

// ИЛИ

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)


Используйте данный метод для подготовки файла в двоичном формате и его последующей отправки в запросе.


Параметры:

НазваниеТипОбязательныйЗначение по умолчаниюОписание
contentStringДаНетДанные двоичного файла в кодировке base64.
paramNameStringДаНетНазвание параметра в запросе POST, который передает двоичные данные.
fileNameStringДаНетНазвание файла


Info

В один запрос можно добавить несколько файлов. В этом случае название параметра запроса POST должно представлять собой массив элементов. Например, если используется только один файл, параметр может называться files. Если используются два файла, их следует называть files[1] и files[2].

Возвращаемое значение:

ТипОписание
VoidДанный метод не возвращает значение.

Примеры:

Code Block
languagejs
themeEclipse
titleAdding two filesДобавление двух файлов
linenumberstrue
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
languagejs
themeEclipse
titleAdding one fileДобавление одного файла
linenumberstrue
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()


Используйте данный метод для отправки запроса REST.


Возвращаемое значение:

ТипОписание
SimpleRestResponseМетод возвращает значение объекта SimpleRestResponse.


Пример:

Code Block
languagejs
themeEclipse
titleexecute()
linenumberstrue
const request = sws.restRequestV1();
request.setRequestUrl(`https://jsonplaceholder.typicode.com/todos/1`);
request.setRequestMethod('GET');
const response = request.execute();

setBasicAuth(userName, userPassword)


Используйте этот метод, чтобы настроить имя пользователя для аутентификации веб-службы, если выбран базовый тип аутентификации.


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
userNameStringДаНет
userPasswordStringДаНет


Возвращаемое значение:

ТипОписание
VoidДанный метод не возвращает значение.


Пример:

Code Block
languagejs
themeEclipse
titlesetBasicAuth()
linenumberstrue
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...


Фрагмент кода ниже демонстрирует, как получить токен авторизации с логином и паролем пользователя. В коде используются примеры данных для метода setRequestUrl(requestUrl) и константы payload. Замените его реальными данными перед использованием.

Code Block
languagejs
themeEclipse
titleAuth methodМетод авторизации
linenumberstrue
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().


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
requestUrlStringДаНет


Возвращаемое значение:

ТипОписание
VoidДанный метод не возвращает значение.


Пример:

Code Block
languagejs
themeEclipse
titlesetRequestUrl()
linenumberstrue
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)


Используйте данный метод, чтобы задать метод запроса (GET, POST, PURGE и пр.) Укажите название метода в параметреmethodNameДля того, чтобы получить название метода, используйте метод  getRequestMethod().


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
methodNameStringДаНет


Возвращаемое значение:

ТипОписание
VoidДанный метод не возвращает значение.


Пример:

Code Block
languagejs
themeEclipse
titlesetRequestMethod()
linenumberstrue
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)


Устанавливает таймаут ответа запроса в секундах.


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
timeoutIntegerДаНет


Возвращаемое значение:

ТипОписание
VoidДанный метод не возвращает значение.


Пример:

Code Block
languagejs
themeEclipse
titlesetRequestTimeout()
linenumberstrue
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)


Используйте этот метод, чтобы добавить параметр в конец URL запроса, сгенерированного как "name=value".


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
nameStringДаНет
valueStringДаНет


Возвращаемое значение:

ТипОписание
VoidДанный метод не возвращает значение.


Пример:

Code Block
languagejs
themeEclipse
titlesetQueryParameter()
linenumberstrue
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.

Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
bodyStringДаНет


Возвращаемое значение:

ТипОписание
VoidДанный метод не возвращает значение.


Пример:

Code Block
languagejs
themeEclipse
titlesetRequestBody()
linenumberstrue
const recordURL =
    ss.getProperty('simple.instance.uri') + '/record/' + current.getTableName() + '/' + current.sys_id;
const dataJSON = {
    'text': `Новый запрос назначен на команду DevOps <${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)


Используйте этот метод, чтобы установить переменную запроса с именем, указанным из записи, в указанное значение.


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
nameStringДаНет
valueStringДаНет


Возвращаемое значение:

ТипОписание
VoidДанный метод не возвращает значение.


Пример:

Code Block
languagejs
themeEclipse
titlesetStringParameter
linenumberstrue
/* 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();

setRequestHeader(name, value)


Используйте данный метод, чтобы установить заголовок HTTP в запросе с указанным значением. Чтобы получить заголовки запроса, используйте метод getRequestHeaders().


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
nameStringДаНет
valueStringДаНет


Возвращаемое значение:

ТипОписание
VoidДанный метод не возвращает значение.


Пример:

Code Block
languagejs
themeEclipse
titlesetRequestHeader()
linenumberstrue
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-адрес запроса, используйте метод setRequestUrl(requestUrl).


Возвращаемое значение:

ТипОписание
StringURL-адрес запроса


Пример:

Code Block
languagejs
themeEclipse
titlegetRequestUrl()
linenumberstrue
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()


Используйте этот метод, чтобы вернуть тело запроса. Чтобы установить тело запроса, используйте метод setRequestBody(body).


Возвращаемое значение:

ТипОписание
StringТело запроса


Пример:

Code Block
languagejs
themeEclipse
titlegetRequestBody
linenumberstrue
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>"}

getRequestHeaders()


Испольуйте этот Используйте этот метод, чтобы вернуть все заголовки запроса. Чтобы установить заголовки запроса, используйте метод setRequestHeader(name, value).


Возвращаемое значение:

ТипОписание
ArrayЗаголовки запроса


Пример:

Code Block
languagejs
themeEclipse
titlegetRequestHeaders()
linenumberstrue
const request = sws.restRequestV1();
request.setRequestHeader('Content-type', 'application/json');
const header = request.getRequestHeaders();
ss.info(header);
// InfoИнформация: {"content-type":["application\/json"]}

getRequestMethod()


Используйте этот метод, чтобы вернуть метод запроса. Чтобы установить метод запроса, используйте метод setRequestMethod(methodName).


Возвращаемое значение:

ТипОписание
StringНазвание метода


Пример:

Code Block
languagejs
themeEclipse
titlegetRequestMethod()
linenumberstrue
const request = sws.restRequestV1();
request.setRequestMethod('GET');
const method = request.getRequestMethod();
ss.info(method);
//InfoИнформация: GET

useHttp2(value)


Используйте этот метод, чтобы сделать протокол HTTP/2 обязательным. 

Note

При использовании этого метода необходимо, чтобы хост поддерживал протокол HTTP/2.

Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
valuebooleanНетtrue

Возвращаемое значение:

ТипОписание
VoidДанный метод не возвращает значение.

Пример:

Code Block
languagejs
themeEclipse
titleuseHttp2()
linenumberstrue
const request = sws.restRequestV1();
request.setRequestUrl('https://http2.pro/api/v1');
request.setRequestMethod('GET');
request.useHttp2();
const response = request.execute();


Чтобы отключить использование HTTP/2, необходимо вызвать метод, передав параметр "false".

Code Block
languagejs
themeEclipse
titleuseHttp2()
linenumberstrue
request.useHttp2(false);


Table of Contents
absoluteUrltrue
classfixedPosition