Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call REST from jenkins workflow

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.

like image 343
Assen Kolov Avatar asked Jan 08 '16 16:01

Assen Kolov


People also ask

How do I access REST API Jenkins?

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.

Does Jenkins have a REST API?

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.

How do I interact with Jenkins API?

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.


2 Answers

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()); } 
like image 186
Jim Perris Avatar answered Sep 28 '22 03:09

Jim Perris


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) 
like image 43
raitisd Avatar answered Sep 28 '22 04:09

raitisd