Problem:
I want to automatically add custom field options for a single-choice select-list using scriptrunner.
I have already written the following script, which is based on this page:
PUT-Update custom field options (context)
Script:
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
// Jira Configuration
def baseUrl = "[Jira URL]"
def apiToken = "[My API Token]"
def email = "[My Username]"
// Authentication
def authString = "${email}:${apiToken}".bytes.encodeBase64().toString()
def headers = [
"Authorization": "Basic ${authString}",
"Content-Type": "application/json",
"Accept": "application/json"
]
// Data for the POST request
def bodyData = '''
{
"options": [
{
"disabled": false,
"value": "Scranton"
},
{
"disabled": true,
"optionId": "10000",
"value": "Manhattan"
},
{
"disabled": false,
"value": "The Electric City"
}
]
}
'''
// Function to execute an HTTP request
def sendHttpRequest(urlStr, method, headers, body = null) {
def url = new URL(urlStr)
def connection = url.openConnection() as HttpURLConnection
connection.requestMethod = method
headers.each { k, v -> connection.setRequestProperty(k, v) }
if (body) {
connection.doOutput = true
connection.outputStream.withWriter { it << body }
}
def responseCode = connection.responseCode
def responseMessage = connection.responseMessage
def responseText = connection.inputStream.text
return [responseCode: responseCode, responseMessage: responseMessage, responseText: responseText]
}
// ID of the field and context
def fieldId = "customfield_12345"
def contextId = "56789"
def url = "${baseUrl}/rest/api/3/field/${fieldId}/context/${contextId}/option"
def response = sendHttpRequest(url, 'POST', headers, bodyData)
// Output the API response for debugging
println "Response Code: ${response.responseCode}"
println "Response Message: ${response.responseMessage}"
println "Response Text: ${response.responseText}"
// Parse the JSON response (if necessary)
def jsonSlurper = new JsonSlurper()
def jsonResponse = jsonSlurper.parseText(response.responseText)
println JsonOutput.prettyPrint(JsonOutput.toJson(jsonResponse))
This script throws the following error:
java.io.IOException: Server returned HTTP response code: 400 for URL: ...
With a GET query I don't get this error and it gives me the context values. What could be the reason that I cannot add any options, although they can also be read.
Thanks in Advance,
Tim