Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Next challenges

Recent achievements

Recognition

  • Give kudos
  • My kudos

Leaderboard

  • Global

Trophy case

Kudos (beta program)

Kudos logo

You've been invited into the Kudos (beta program) private group. Chat with others in the program, or give feedback to Atlassian.

View group

It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

REST API call with Script Runner in Script Listener Edited

Hi,

I'm trying to post a simple REST API call (hard-coded issue creation) to a test instance via Script Runner. The call should actually happen in a Script Listener but for debugging I'm using the Script Console. Unfortunately I'm stuck with a HTTP 400 response althought the call is successful using Postman.

import groovy.json.StreamingJsonBuilder
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import java.text.SimpleDateFormat
import java.text.DateFormat
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.comments.CommentManager

def baseURL = "http://test2.mydomain:8080/rest/api/2/issue/"; 

def body_req = [
"""
{ "fields":
 {
  "project": {"key": "ABC"},
  "issuetype": {"name": "Bug"},
  "summary": "My Issue.",
  "description": "Test"
 }
}
"""
]

URL url = new URL(baseURL);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setRequestProperty( "Authorization", "Basic T****************************************************************4" );
connection.requestMethod = "POST";
connection.doOutput = true;
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.outputStream.withWriter("UTF-8") { new StreamingJsonBuilder(it, body_req) }
connection.connect();

println("url: " + url);
println("Content:" + connection.getContent())
println("ResponseCode:" + connection.getResponseCode())
println("getResponseMessage:" + connection.getResponseMessage())

Outcome:

java.io.IOException: Server returned HTTP response code: 400 for URL: http://test2.mydomain:8080/rest/api/2/issue/
 at java_net_URLConnection$getContent.call(Unknown Source)
 at Script337.run(Script337.groovy:36)

 

In Postman it works:

111.png

Jira Core 7.12.3
Script Runner 5.4.48

Thanks for your help!
Cheers, Tom

2 answers

I found a solution

def baseurl = ComponentAccessor.getApplicationProperties().getString("jira.baseurl")
def authString = "llll:pppp".bytes.encodeBase64().toString()
def remote = new HTTPBuilder(baseurl+"/rest/configuration-manager/api/1.3/snapshots")
def issueJson = remote.request(Method.POST, ContentType.JSON) { req ->
headers."Authorization" = "Basic ${authString}"
body = [ name :" My Project Snapshot",
description : "project snapshot",
scope : "projectWithIssues",
projectKey : ["XXXX"],
filters : [],
agileBoards : [],
dashboards : []
]
response.success = { resp, json ->
log.warn("Successful = " + json.messages)
}
response.failure = { resp, json ->
log.warn("Failed = " + json.messages)
}
}

Thanks! It works for me. I've only refactored it for posting pages into Confluence through REST API.

Excelent! It works for me 

1 vote
Ian Atlassian Team Mar 12, 2019

Hello @Tom104Tom ,

 

You might want to try this approach

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import groovyx.net.http.ContentType
import static groovyx.net.http.Method.*

def http = new HTTPBuilder('http://localhost:2990/jira/rest/api/2/issue')
def authString = "admin:admin".getBytes().encodeBase64().toString();
http.request(POST, ContentType.JSON) {
requestContentType = ContentType.JSON
request.addHeader("authorization: Basic ${authString}", "ContentType: application/json")
body = [ fields:
"{\"project\": {\"key\": \"MIS\"},\"issuetype\": {\"name\": \"Task\"}, \"summary\": \"My new task hello world\",\"description\": \"Test\"}"
]
response.success = { resp, JSON ->
log.warn("Successful = " + JSON)
}

response.failure = { resp, JSON ->
log.warn("Failed = " + JSON)
}
}

This worked for me. Try it out and tell me how it goes.

 

Cheers,

Ian

@Ian 

I am getting errors as requestContentType is undeclared if I am trying with above code

Ian Atlassian Team Apr 21, 2019

Hello @Vineela Durbha,

 

Can you show the exact code you used and the error you got? Thanks.

Hello i'm trying to use this webservice in scriptrunner : "http://localhost:8081/rest/configuration-manager/api/1.3/snapshots"

it works fine with my rest api browser with this body 

{
"name" : "My Project Snapshot with 13",
"description" : "Interesting snapshot",
"scope" : "projectWithIssues",
"projectKey" : ["EBDODI"],
"filters" : [ ],
"agileBoards" : [ ],
"dashboards" : [ ],
"options" : {
"checkCustomFieldValues" : true,
"includeAttachmentFiles" : true
}
}

but in script runner i get this

 

2019-09-09 13:17:34,686 WARN [common.UserScriptEndpoint]: Script console script failed: groovyx.net.http.ResponseParseException: at groovyx.net.http.HTTPBuilder$1.handleResponse(HTTPBuilder.java:495) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:223) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:165) at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:515) at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:434) at groovyx.net.http.HTTPBuilder.request(HTTPBuilder.java:383) at groovyx.net.http.HTTPBuilder$request.call(Unknown Source) at Script101.run(Script101.groovy:19) Caused by: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object The current character read is '<' with an int value of 60 Unable to determine the current character, it is not a string, number, array, or object line number 1 index number 0 <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>Oops - an error has occurred</title><script type="text/javascript">contextPath = "";</script><link type='text/css' rel='stylesheet' href='/static-assets/metal-all.css' media='all'><script src='/static-assets/jquery-min.js'></script><script src='/static-assets/metal-all.js'></script><meta name="decorator" content="none" /></head><body class=" error-page error500"><script type="text/javascript">document.body.className += " js-enabled";</script><div id="page"><header id="header" role="banner"></header><!-- #header --><section id="content" role="main"><div class="aui-page-panel"><div class="aui-page-panel-inner"><section class="aui-page-panel-content lowerContent"><div id="error-state"><span class="error-type"></span><h1>Sorry, we had some technical problems during your last operation.</h1><h2 class="technical-details-header"><span>Request assistance</span></h2><div id="technical-details-content" class="technical-details js-hidden"><p>Copy the content below and send it to your Jira Administrator</p><div class="technical-details-content" contentEditable readonly><h2>Technical details</h2><p class="referral">Log&#39;s referral number: <strong id="log-referral-id">e8addb10-2555-48f1-96a5-236f0ef8954a</strong></p><div class="info-section" id="causePanel"><h2>Cause</h2><p>Referer URL: <b>Unknown</b></p><pre>java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 16</pre><blockquote id="stacktrace" style="overflow-x: auto;"><pre>java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 16 ^

 this is my code :

def http = new HTTPBuilder('http://localhost:8081/rest/configuration-manager/api/1.3/snapshots') 
def authString = "admin:admin".getBytes().encodeBase64().toString();
http.request(POST, ContentType.JSON) {
requestContentType = ContentType.JSON
request.addHeader("authorization: Basic ${authString}", "ContentType: application/json")
body = [
"{'name' : 'My Project Snapshot with Issues','description' : 'Interesting snapshot','scope' : 'projectWithIssues','projectKey' : 'EBDODI', 'filters' : [],'agileBoards' : [],'dashboards' : [],'options' : {'checkCustomFieldValues' : 'true','includeAttachmentFiles': 'true'}}"
]
response.success = { resp, JSON ->
log.warn("Successful = " + JSON)
}

response.failure = { resp, JSON ->
log.warn("Failed = " + JSON)
}
}

Suggest an answer

Log in or Sign up to answer
TAGS
Community showcase
Asked in Jira Service Desk

Calling all Insight users, we need your help!

Hello Insight users,  As part of our (Mindville's) acquisition by Atlassian, our training team is looking to build some new Insight training materials. It would really helpful if you can ...

161 views 1 1
View question

Community Events

Connect with like-minded Atlassian users at free events near you!

Find an event

Connect with like-minded Atlassian users at free events near you!

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you