Getting all Spaces with a Label

Tried a couple of approaches, but cannot seem to get it right.

Add Labels To Spaces In Bulk - Adaptavist Library shows how to add a label to a space and there is a method in the LabelManager to getSpacesByLabel (LabelManager (Atlassian Confluence 5.9.8 API)), but no matter how I try, I cannot get it to work. Here’s my current attempt. Any thoughts?

/////
// ScriptRunner libraries
import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import com.onresolve.scriptrunner.runner.ScriptRunnerImpl

import groovy.json.JsonBuilder
import groovy.transform.BaseScript
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response

/////
// Confluence libraries
import com.atlassian.confluence.spaces.Space
import com.atlassian.confluence.labels.Label
import com.atlassian.confluence.labels.LabelManager

@BaseScript CustomEndpointDelegate delegate

final LabelManager labelManager = ScriptRunnerImpl.getPluginComponent(LabelManager)

getSpaces(httpMethod: "GET") {
    MultivaluedMap queryParams, String body ->
    
    String labelName = queryParams.label.get(0)
    Label spaceLabel = labelManager.getLabel(labelName)

    if (!spaceLabel) {
      return Response.serverError().entity([error: "Could not find label with name '"+labelName+"'"]).build()
    }
    List<Space> spaces = labelManager.getSpacesWithLabel(spaceLabel)

    // loop through the list of spaces
    List<String> output = spaces.each { space -> output.push(space.getName())}

    final def jsonOutput = new JsonBuilder(output.sort()).toString()
    Response.ok(jsonOutput).build()
}

The guide here https://community.atlassian.com/t5/Confluence-articles/Get-spaces-by-keys-with-the-Confluence-API/ba-p/1939901 uses a completely different set of interfaces, but the Label model doesn’t seem compatible.

I’m not sure how to reconcile the two approaches

Hi mullenix,

Instead of using the getLabel method, you can try to get a label for a space using the getTeamLabels method:

Label spaceLabel = labelManager.getTeamLabels("labelName")
...
List<Space> spaces = labelManager.getSpacesWithLabel(spaceLabel)

Basically, team labels are space categories, see these links: