Accessing REST API Endpoints Using Scriptrunner for Confluence Server/DC

I’ve written before about accessing REST APIs using Scriptrunner for Jira DC.   Frankly, I think the solution was a bit over-complicated.

Let’s take a look at accessing REST API endpoints, using ScriptRunner for Confluence.   Specifically, we’re going to use it to return user macro usage information.

The code below is the basic, foundational approach to running a GET request using ScriptRunner.  You don’t need to authenticate if you’re running the script from within the same browser that holds your current Confluence login session.

Additionally, this fetches JSON that represents the usage of a given user macro. All we need to do is complete the URL below, including the Jira hostname and the name of the macro.

import java.net.HttpURLConnection
import java.net.URL
import import groovy.json.JsonSlurper

def apiUrl = 'https://<jira-url>.com/rest/api/content/search?cql=macro+%3D+"<macroName>"'
try {
    URL url = new URL(apiUrl)
    HttpURLConnection connection = (HttpURLConnection) url.openConnection()
    connection.setRequestMethod("GET")
    connection.setRequestProperty("Content-Type", "application/json")
    int responseCode = connection.getResponseCode()
    if (responseCode == HttpURLConnection.HTTP_OK) {
        def response = connection.inputStream.text
        def jsonSlurper = new JsonSlurper()
        def jsonResponse = jsonSlurper.parseText(response)
    } else {
        log.error("Error calling the API. Response Code: $responseCode")
    }
    connection.disconnect()
} catch (Exception e) {
    log.error("An error occurred: ${e}")
}
jsonResponse.results.each{macroResult ->
log.warn(macroResult)
}

Leave a Reply

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