ScriptRunner Foundations – Accessing Jira REST API Using Groovy

Overview

Please note: this solution was originally posted by Peter-Dave Sheehan on the Atlassian Forums. I’m just explaining how I use it.

 

Sometimes when I’m trying to solve a problem with Jira, the internal Java libraries just aren’t sufficient. They’re often not documented, or they’re opaque. 

It’s often far easier to turn to the REST API to get work done, but that’s a little more tricky on Jira DC or Server than it is on Cloud.  On Jira Cloud, a REST call could be as simple as:

def result = get("/rest/api/2/issue/<issue key>")
.header('Content-Type', 'application/json')
.asObject(Map)

result.body.fields.comment.comments.body.each{field->
       return field
    }
}

 

However this won’t work on Server/DC.  Instead we need a REST framework upon which to build our script.

The Framework

This piece of code uses the currently logged in user to authenticate against the Jira REST API.  It then makes a GET call to the designated API endpoint URL.

This code can easily be changed to a POST or a PUT simply by uncommenting the payload statement and the setRequestBody statement, then changing the MethodType from GET to POST/PUT
 

The script returns a JSON blob. With point notation, we can then easily access its individual attributes, and start working with the values therein.

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.config.properties.APKeys
import com.atlassian.sal.api.net.Response
import com.atlassian.sal.api.net.ResponseException
import com.atlassian.sal.api.net.ReturningResponseHandler
import com.atlassian.sal.api.net.TrustedRequest
import com.atlassian.sal.api.net.TrustedRequestFactory
import com.atlassian.sal.api.net.Request
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import groovyx.net.http.ContentType
import groovyx.net.http.URIBuilder
import java.net.URL;
import java.nio.file.Path;


def currentUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser
def baseUrl = ComponentAccessor.applicationProperties.getString(APKeys.JIRA_BASEURL)
def trustedRequestFactory = ComponentAccessor.getOSGiComponentInstanceOfType(TrustedRequestFactory)
 
//def payload = new JsonBuilder([payloadField: 'payload value']).toString()
def endPointPath = '/rest/api/2/issue/<issue key>'
def url = baseUrl + endPointPath
 
def request = trustedRequestFactory.createTrustedRequest(Request.MethodType.GET, url) as TrustedRequest
request.addTrustedTokenAuthentication(new URIBuilder(baseUrl).host, currentUser.name)
request.addHeader("Content-Type", ContentType.JSON.toString())
request.addHeader("X-Atlassian-Token", 'no-check')
//request.setRequestBody(payload)
 
def response = request.executeAndReturn(new ReturningResponseHandler<Response, Object>() {
    Object handle(Response response) throws ResponseException {
        if (response.statusCode != HttpURLConnection.HTTP_OK) {
            log.error "Received an error while posting to the rest api. StatusCode=$response.statusCode. Response Body: $response.responseBodyAsString"
            return null
        } else {
            def jsonResp = new JsonSlurper().parseText(response.responseBodyAsString)
            log.info "REST API reports success: $jsonResp"
 
            return jsonResp
             }
        }
    })

Leave a Reply

Your email address will not be published. Required fields are marked *