You are viewing an old version of this page. View the current version.
Compare with Current View Page History
« Previous Version 2 Next »
Используйте этот класс для рабты с методами и параметрами REST API.
SimpleRestRequest()
Данный метод предназначен для создания пустого объекта SimpleRestRequest. При использовании такого объекта укажите метод и конечную точку вручную.
SimpleRestRequest(requestName, methodName)
Этот метод предназначен для создания объекта, используемого в запросах REST. При использовании метода создается объект с префиксом sws (см. пояснение в примере кода ниже).
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
requestName | String | Нет | Нет |
methodName | String | Нет | Нет |
Укажите значения параметров, как показано ниже:
Параметр | Значение |
---|---|
requestName | Укажите значение поля Наименование из записи в таблице Запросы REST (sys_rest_requests). |
methodName | Укажите значение поля Наименование из записи в таблице Методы REST (sys_rest_request_method), относящейся к этому запросу. |
Возвращаемое значение:
Тип | Описание |
---|---|
SimpleRestRequest object | Этот метод возвращает объект SimpleRestRequest, созданный при помощи переданного запроса. В случае ошибки метод возвращает пустой объект SimpleRestRequest. |
Пример:
/* Create the 'Telegram' request in REST Requests (sys_rest_requests) 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 Param (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 | String | Да | Нет | Данные двоичного файла в кодировке base64. |
paramName | String | Да | Нет | Название параметра в запросе POST, который передает двоичные данные. |
fileName | String | Да | Нет | Название файла |
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 files[2].
Возвращаемое значение:
Тип | Описание |
---|---|
Void | Данный метод не возвращает значение. |
Примеры:
const request = sws.restRequestV1(); request.setRequestUrl('https://instance.example1.com/some/service'); //the URL from which the files are downloaded 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();
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. |
Пример:
const request = sws.restRequestV1(); request.setRequestUrl(`https://jsonplaceholder.typicode.com/todos/1`); request.setRequestMethod('GET'); const response = request.execute();
setBasicAuth(userName, userPassword)
Используйте этот метод, чтобы настроить имя пользователя для аутентификации веб-службы, если выбран базовый тип аутентификации.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
userName | String | Да | Нет |
userPassword | String | Да | Нет |
Возвращаемое значение:
Тип | Описание |
---|---|
Void | Данный метод не возвращает значение. |
Пример:
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) и константы полезной нагрузки. Замените его реальными данными перед использованием.
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().
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
requestUrl | String | Да | Нет |
Возвращаемое значение:
Тип | Описание |
---|---|
Void | Данный метод не возвращает значение. |
Пример:
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.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
methodName | String | Да | Нет |
Возвращаемое значение:
Тип | Описание |
---|---|
Void | Данный метод не возвращает значение. |
Пример:
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.
Параметры:
Name | Type | Обязательный | Значение по умолчанию |
---|---|---|---|
timeout | Integer | Y | 60 |
Возвращаемое значение:
Type | Описание |
---|---|
Void | Данный метод не возвращает значение. |
Пример:
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 "name=value".
Параметры:
Name | Type | Обязательный | Значение по умолчанию |
---|---|---|---|
name | String | Y | N |
value | String | Y | N |
Возвращаемое значение:
Type | Описание |
---|---|
Void | Данный метод не возвращает значение. |
Пример:
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)
Sets the request body when the PUT or POST methods are used. To get the request body, use the GET method.
Параметры:
Name | Type | Обязательный | Значение по умолчанию |
---|---|---|---|
body | String | Y | N |
Возвращаемое значение:
Type | Описание |
---|---|
Void | Данный метод не возвращает значение. |
Пример:
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.
Параметры:
Name | Type | Обязательный | Значение по умолчанию |
---|---|---|---|
name | String | Y | N |
value | String | Y | N |
Возвращаемое значение:
Type | Описание |
---|---|
Void | Данный метод не возвращает значение. |
Пример:
/* Create the 'Telegram' request in REST Requests (sys_rest_requests) 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 Param (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)
Sets the HTTP header in the request with the value specified. To get request headers, use the getRequestHeaders() method.
Параметры:
Name | Type | Обязательный | Значение по умолчанию |
---|---|---|---|
name | String | Y | N |
value | String | Y | N |
Возвращаемое значение:
Type | Описание |
---|---|
Void | Данный метод не возвращает значение. |
Пример:
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()
Displays the request URL with parameters. To set a request URL, use the setRequestUrl(requestUrl) method.
Возвращаемое значение:
Type | Описание |
---|---|
String | The request URL. |
Пример:
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.
Возвращаемое значение:
Type | Описание |
---|---|
String | The request body. |
Пример:
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()
Returns all request headers. To set request headers, use the setRequestHeader(name, value) method.
Возвращаемое значение:
Type | Описание |
---|---|
Array | The requested headers. |
Пример:
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.
Возвращаемое значение:
Type | Описание |
---|---|
String | The method name. |
Пример:
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.
Using this methods requires the host that also supports the HTTP/2 protocol.
Параметры:
Name | Type | Обязательный | Значение по умолчанию |
---|---|---|---|
value | boolean | N | true |
Возвращаемое значение:
Type | Описание |
---|---|
Void | Данный метод не возвращает значение. |
Пример:
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.
request.useHttp2(false);
- No labels