I wonder how to call REST API from a (groovy) Jenkins workflow script. I can execute "sh 'curl -X POST ...'" - it works, but building the request as a curl command is cumbersome and processing the response gets complicated. I'd prefer a native Groovy HTTP Client to program in groovy - which one should I start with? As the script is run in Jenkins, there is the step of copying all needed dependency jars to the groovy installation on Jenkins, so something light-weight would be appreciated.
Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.
It is up to the user to parse the JSON and extract the relevant pieces. Interestingly, Jenkins itself has a REST API, so a Pipeline DSL could use the http request plugin to talk to the master Jenkins instance from an agent. But the user still to parse the response.
Using Curl If your Jenkins server requires authentication (and it SHOULD), you'll see a message saying "Authentication Required". The Jenkins API uses HTTP BASIC authentication and requires a username as well as an API token to connect. Then click the box named "Show API Token", and copy the token to your clipboard.
Native Groovy Code without importing any packages:
// GET def get = new URL("https://httpbin.org/get").openConnection(); def getRC = get.getResponseCode(); println(getRC); if(getRC.equals(200)) { println(get.getInputStream().getText()); } // POST def post = new URL("https://httpbin.org/post").openConnection(); def message = '{"message":"this is a message"}' post.setRequestMethod("POST") post.setDoOutput(true) post.setRequestProperty("Content-Type", "application/json") post.getOutputStream().write(message.getBytes("UTF-8")); def postRC = post.getResponseCode(); println(postRC); if(postRC.equals(200)) { println(post.getInputStream().getText()); }
There is a built in step available that is using Jenkins HTTP Request Plugin to make http requests.
Plugin: https://wiki.jenkins-ci.org/display/JENKINS/HTTP+Request+Plugin
Step documentation: https://jenkins.io/doc/pipeline/steps/http_request/#httprequest-perform-an-http-request-and-return-a-response-object
Example from the plugin github page:
def response = httpRequest "http://httpbin.org/response-headers?param1=${param1}" println('Status: '+response.status) println('Response: '+response.content)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With