Использование внешних API в SR - malikovalibek/groovyForJira GitHub Wiki
Обзор Этот сценарий можно использовать в качестве шаблона для выполнения наиболее распространенных внешних системных вызовов, таких как: получение ответа, создание данных, обновление данных или удаление элемента в этой внешней системе с помощью ее REST API.
пример Я отвечаю за внедрение проекта Jira в компанию. Каждый раз, когда в нашу внешнюю кадровую систему добавляется новый сотрудник, я хочу получить информацию об этом сотруднике. Я могу использовать этот сценарий для подключения к REST API внешней системы и получения необходимых данных.
Хорошо знать Внешнюю систему можно настроить с учетом необходимых требований. В этом примере спецификации внешней системы: Метод GET использует аутентификацию на основе токенов, добавленную в качестве заголовка. При использовании метода POST для аутентификации используется специальный заголовок. Метод PUT использует базовую аутентификацию. Метод DELETE не аутентифицирован. Параметры запроса могут быть добавлены в строку "" или могут быть добавлены в каждый метод (GET, POST, PUT, DELETE) с соответствующими клиентскими методами HTTP. (Сервер) Результаты обрабатываются пользовательскими обработчиками, связанными с клиентом. Эти обработчики управляли успешными и ошибочными ответами, сохраняя ответ JSON в случае успеха и записывая ошибку в журнал, если это был сбой. (Сервер) Перейдите по этой ссылке для получения дополнительной информации о RESTClient. (Облако) Полученные результаты сохраняются в карте (за исключением метода DELETE, у которого нет тела ответа), но могут быть сохранены в списке, если конечная точка возвращает список объектов или необходимый объект, с использованием asObjectметода. (Облако) Перейдите по этой ссылке, чтобы получить дополнительную информацию о Unirest-JavaHTTP-клиенте, используемом Jira Cloud.
import groovy.json.JsonOutput import groovyx.net.http.ContentType import groovyx.net.http.HttpResponseDecorator import groovyx.net.http.RESTClient
import static groovyx.net.http.Method.*
final externalUrl = "https:///"
// Turn the data will be sent into JSON, the HTTP requests specify in the header to accept application/JSON // If the API accepts different types then you can change this and format the data accordingly def body = JsonOutput.toJson([data: ""])
// The host URL will be the consistent prefix to every request is made. i.e: https:/// // The endpoint will be the specific API method to hit. i.e: /GetResults // The query will be the variable parameter the endpoint will use to get the data. i.e: /objectId=1 // The body is the JSON version of the data that will be sent to an API, only used for PUT and POST def getResponse = get(externalUrl, "") def postResponse = post(externalUrl, "", body) def putResponse = put(externalUrl, "", body) def deleteResponse = delete(externalUrl, "")
// If GET response is successful then the response can be cast to a Map which will allow to interact with the data if (getResponse) { def responseGetMap = getResponse as Map // A code to manage the resulted data can be inserted here, i.e iterate results with responseMap.each{} responseGetMap.each {}
def responsePostMap = postResponse as Map // A code to manage the resulted data can be inserted here, i.e iterate results with responseMap.each{} responsePostMap.each {}
def responsePutMap = putResponse as Map // A code to manage the resulted data can be inserted here, i.e iterate results with responseMap.each{} responsePutMap.each {}
def responseStatus = deleteResponse as Integer // In this case, status is returned as delete HTTP method responds an empty body assert responseStatus == 200 }
def get(def hostUrl, def endpointAndQuery) { // If authentication mechanism of the API is token-based, it can be specified into this variable def token = "" def client = new RESTClient(hostUrl) client.setHeaders([ 'Accept' : ContentType.JSON, // The 'Authorization' header is added 'Authorization': "Bearer $token" ]) client.handler.success = { HttpResponseDecorator response, json -> json } client.handler.failure = { HttpResponseDecorator response -> // Failure can be handled here log.error response.entity.content.text [:] } client.get( path: endpointAndQuery, contentType: ContentType.JSON ) }
def post(def hostUrl, def endpointAndQuery, def bodyJson) { def client = new RESTClient(hostUrl) client.setHeaders([ 'Accept' : ContentType.JSON, // If authentication mechanism of the API requires a special header, it can be added here 'x-api-key': '' ]) client.handler.success = { HttpResponseDecorator response, json -> json } client.handler.failure = { HttpResponseDecorator response -> // Failure can be handled here log.error response.entity.content.text [:] } client.post( path: endpointAndQuery, contentType: ContentType.JSON, body: bodyJson ) }
def put(def hostUrl, def endpointAndQuery, def bodyJson) { def client = new RESTClient(hostUrl) client.setHeaders([ 'Accept' : ContentType.JSON, // If authentication mechanism of the API is Basic Authentication, 'Authorization' header with username and password encoded as Base 64 can be specified here 'Authorization': "Basic ${':'.bytes.encodeBase64().toString()}" ]) client.handler.success = { HttpResponseDecorator response, json -> json } client.handler.failure = { HttpResponseDecorator response -> // Failure can be handled here log.error response.entity.content.text [:] } client.put( path: endpointAndQuery, contentType: ContentType.JSON, body: bodyJson ) }
def delete(def hostUrl, def endpointAndQuery) { def client = new RESTClient(hostUrl) client.setHeaders([ 'Accept': ContentType.JSON, ]) client.handler.success = { HttpResponseDecorator response -> response.statusLine.statusCode } client.handler.failure = { HttpResponseDecorator response -> // Failure can be handled here log.error response.entity.content.text [:] } client.delete( path: endpointAndQuery, contentType: ContentType.JSON ) }