Need Help in sending external API calls from Scriptrunner

Vikrant Yadav
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
March 21, 2023

Hi Guys,

Need your help in sending REST API from Scriptrunner script console. 

I'm trying to see below POST HTTP request, but getting 404 error. I think some issue in my code, please help me in fixing the code :- 

import groovy.json.JsonOutput

import groovyx.net.http.ContentType

import groovyx.net.http.HttpResponseDecorator

import groovyx.net.http.RESTClient

final externalUrl = "https://api.openai.com/v1/completions/"

def body = JsonOutput.toJson(

          """{

  "model": "text-davinci-003",

  "prompt": "Q:do you know if we have an Advanced Roadmap plugin running in Jira cloudand please share latest Atlassian Document Link?AI:",

  "temperature": 0,

  "max_tokens": 100,

  "top_p": 1,

  "frequency_penalty": 0,

  "presence_penalty": 0,

  "stop": ["\n"]

}""")

def postResponse = post(externalUrl, "", body)

/*

if (getResponse) {

        def responsePostMap = postResponse as Map

      responsePostMap.each {}

   

    assert responseStatus == 200

}*/

def post (def hostUrl, def endpointAndQuery, def bodyJson)

{

  def client = new RESTClient(hostUrl)

     client.setHeaders([

        'Accept'        : ContentType.JSON,

        'Authorization' : "Bearer sk-j4qZQqwSRgElbkFJbALfxVk99xgsfiJmTlm4"

          ])

    client.post(

        path: endpointAndQuery,

        contentType: ContentType.JSON,

        body: bodyJson

    )

}

1 answer

1 accepted

1 vote
Answer accepted
Peter-Dave Sheehan
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
March 21, 2023

You should let the RESTClient handle the body conversion.
Just create a groovy map object and pass that as the body. 

import groovy.json.JsonOutput
import groovyx.net.http.ContentType
import groovyx.net.http.RESTClient

final externalUrl = "https://api.openai.com/v1/completions/"

def body = [
model: "text-davinci-003",
prompt: "Q:do you know if we have an Advanced Roadmap plugin running in Jira cloud and please share latest Atlassian Document Link?AI:",
temperature: 0,
max_tokens: 100,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
stop: ["\n"]
]

def postResponse = post(externalUrl, "", body)


def post(def hostUrl, def endpointAndQuery, def bodyJson) {

def client = new RESTClient(hostUrl)
client.setHeaders([
'Accept' : ContentType.JSON,
'Authorization': "Bearer sk-j4qZQqwSRgElbkFJbALfxVk99xgsfiJmTlm4"
])

client.post(
path: endpointAndQuery,
contentType: ContentType.JSON,
body: bodyJson
)
}

If you still get an error, then check back on the documentation of the target endpoint. 
404 usually means that you have specific a wrong endpoint.

 

Radek Dostál
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.
March 21, 2023

Or ask an OpenAI bot to fix the problem?

Like Vikrant Yadav likes this
Vikrant Yadav
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
March 21, 2023

Hi @Peter-Dave Sheehan  and @Radek Dostál  Thanks for your help!
But still getting error while same POST request is working fine in POSTMAN. 

Error Message :- groovyx.net.http.HttpResponseException: status code: 404, reason phrase: Not Found at groovyx.net.http.RESTClient.defaultFailureHandler(RESTClient.java:263) at groovyx.net.http.HTTPBuilder$1.handleResponse(HTTPBuilder.java:503) 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.RESTClient.post(RESTClient.java:141) at groovyx.net.http.RESTClient$post.call(Unknown Source) at Script1959.post(Script1959.groovy:34) at Script1959.run(Script1959.groovy:21)

This is the working cURL command, you can test on your machine as well , it works fine :- 

curl --location 'https://api.openai.com/v1/completions' \

--header 'Content-Type: application/json' \

--header 'Authorization: Bearer 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' \

--data '{

  "model""text-davinci-003",

  "prompt""\\n\\nHuman:do you know if we have an Advanced Roadmap plugin running in Jira cloud and please share latest Atlassian Document Link?\\nAI:",

  "temperature"0.9,

  "max_tokens"150,

  "top_p"1,

  "frequency_penalty"0,

  "presence_penalty"0.6,

  "stop"[" Human:", " AI:"]

}'

Screenshot 2023-03-22 111938.png

Peter-Dave Sheehan
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
March 22, 2023

Ah I see, the other issue was that you can't include the path in the URL when creating the client then try to set it to empty when calling the post method.

Try it like this (I also added a failure handler):

import groovy.json.JsonOutput
import groovyx.net.http.ContentType
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient

final externalUrl = "https://api.openai.com"

def body = [
model: "text-davinci-003",
prompt: "Q:do you know if we have an Advanced Roadmap plugin running in Jira cloud and please share latest Atlassian Document Link?AI:",
temperature: 0,
max_tokens: 100,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
stop: ["\n"]
]

def postResponse = post(externalUrl, "/v1/completions", body)


def post(def hostUrl, def endpointAndQuery, def bodyJson) {
def client = new RESTClient(hostUrl)

client.setHeaders([
'Accept' : ContentType.JSON,
'Authorization': "Bearer sk-j4qZQqwSRgElbkFJbALfxVk99xgsfiJmTlm4"
])

client.handler.failure= { HttpResponseDecorator response ->
log.error "POST Error: $response.uri" //unfortunately, I don't know how to confirm the actual full uri
log.error response.entity.content.text
return [:] //return an empty map
}
client.post(
path: endpointAndQuery,
requestContentType: ContentType.JSON,
body: bodyJson
)
}
Like Vikrant Yadav likes this
Vikrant Yadav
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
March 24, 2023

Thanks, @Peter-Dave Sheehan  

It's working for me. 

Suggest an answer

Log in or Sign up to answer