Come for the products,
stay for the community

The Atlassian Community can help you and your team get more value out of Atlassian products and practices.

Atlassian Community about banner
4,359,836
Community Members
 
Community Events
168
Community Groups

ScriptRunner Script to send object List as body to external API

Hi ,

I'm trying to post some data from JIRA to external system by calling rest API using script Runner.

API expect the List of object. API signature is;

@PostMapping(value="add")
public ResponseEntity<ResponseDTO> postWeightDetails(@RequestBody List<WeightDetail> WeightDetailList)

WeightDetail contains following:

ItemId, Item weight and WeightUnit

So Expected request Body is:

[
  {
    "ItemiD": "ABC-ITEM",
    "weight": 10,
    "weightUnit": "KG"
    
  }
]

Now from JIRA i'm calling this way from RestEnd Point:

 

import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.transform.BaseScript
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import javax.ws.rs.core.Response
import javax.ws.rs.core.MultivaluedMap
import groovyx.net.http.RESTClient
import groovyx.net.http.HttpResponseDecorator

@BaseScript CustomEndpointDelegate delegate

SaveEaseWeightDetails(httpMethod: "POST"){ MultivaluedMap queryParams, String body ->
HTTPBuilder http = new HTTPBuilder("http://localhost:8082/logicalApp/ease/weight/add")

def saveResponse = http.request(Method.POST, ContentType.JSON){
requestContentType = ContentType.JSON
body = [{
"ItemId": "ABC-123",
"weight": 10,
"weightUnit": "KG"}
]

response.success = { resp ->
log.info "Success  ! ${resp.status}"
}
response.failure = { resp, reader ->;
log.error "Failed  : [URI : ${uriPath}, Status: ${resp.status}]"
}
}
return Response.ok(new JsonBuilder(saveResponse).toString())
.header("Access-Control-Allow-Origin", "*").build();

}

 

Script is not working and not finding the issue.

 

1 answer

0 votes

This is a Json string:

[
  {
    "ItemiD": "ABC-ITEM",
    "weight": 10,
    "weightUnit": "KG"
    
  }
]

Here is how you would represent that in groovy:

body = [
[
ItemId : "ABC-123",
weight : 10,
weightUnit: "KG"
]
]

Note the square brackets. In groovy, you define an empty map (object in json) with [:] and an empty list/array with []

The httpbuilder will handle the conversion from the list of maps to a json string of list of objects.

Suggest an answer

Log in or Sign up to answer
TAGS
Community showcase
Published in Jira

Online AMA this week: Your project management questions answered by Jira Design Lead James Rotanson

We know that great teams require amazing project management chops. It's no surprise that great teams who use Jira have strong project managers, effective workflows, and secrets that bring planning ...

171 views 1 6
Read article

Atlassian Community Events