Hello Atlassian Community,
I am wondering what is the base code to set up a POST request to create a JIRA issue/ticket.
I am having trouble setting up the HTTP connection and authentication via Groovy code. Any help would be great! I know the API link/end points but after no clue how to set it up. I already have the payload for the POST request too.
If you want to have a groovy code running on an environment to make a request to itself (i.e. same server/instance), you can use the "TrustedRequestFactory"
Here is a sample script that makes use of that:
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
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/...'
def url = baseUrl + endPointPath
def request = trustedRequestFactory.createTrustedRequest(Request.MethodType.POST, 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
}
}
})
return response
This code example has been immensely helpful to me. Thanks for sharing it!
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
So do I, I have spent hours to get such a code example, many, many thanks !
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.