Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

ScriptRunner Script to send object List as body to external API

ashwani kabra September 16, 2022

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

Suggest an answer

Log in or Sign up to answer
0 votes
PD Sheehan
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
September 16, 2022

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.

TAGS
AUG Leaders

Atlassian Community Events