Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return body of an httpRequest in the Jenkins DSL?

Tags:

jenkins

groovy

I have a step that calls a remote URL successfully using the httpRequest step but, I don't know how to use the body that is returned.

I have set logResponseBody: true but I don't get any output of the body in the console log.

like image 488
Josh Beauregard Avatar asked Feb 12 '18 14:02

Josh Beauregard


1 Answers

httpRequest plugins returns a response object that exposes methods like e.g.

  • Stirng getContent() - response body as String
  • int getStatus() - HTTP status code

You can use JsonSlurper class to parse your response to a JSON object (if the response you are getting back from the request is JSON type). Consider following exemplary pipeline:

import groovy.json.JsonSlurper

pipeline {
    agent any 
    stages {
        stage('Build') { 
            steps {
                script {
                    def response = httpRequest 'https://dog.ceo/api/breeds/list/all'
                    def json = new JsonSlurper().parseText(response.content)

                    echo "Status: ${response.status}"

                    echo "Dogs: ${json.message.keySet()}"
                }
            }
        }
    }
}

In this example we are connecting to open JSON API (https://dog.ceo/api/breeds/list/all) and we display with echo method two things: HTTP status and a list of all dogs in this JSON response. If you run this pipeline in Jenkins you will see something like that in the console log:

[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/test-pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] script
[Pipeline] {
[Pipeline] httpRequest
HttpMethod: GET
URL: https://dog.ceo/api/breeds/list/all
Sending request to url: https://dog.ceo/api/breeds/list/all
Response Code: HTTP/1.1 200 OK
Success code from [100‥399]
[Pipeline] echo
Status: 200
[Pipeline] echo
Dogs: [affenpinscher, african, airedale, akita, appenzeller, basenji, beagle, bluetick, borzoi, bouvier, boxer, brabancon, briard, bulldog, bullterrier, cairn, chihuahua, chow, clumber, collie, coonhound, corgi, dachshund, dane, deerhound, dhole, dingo, doberman, elkhound, entlebucher, eskimo, germanshepherd, greyhound, groenendael, hound, husky, keeshond, kelpie, komondor, kuvasz, labrador, leonberg, lhasa, malamute, malinois, maltese, mastiff, mexicanhairless, mountain, newfoundland, otterhound, papillon, pekinese, pembroke, pinscher, pointer, pomeranian, poodle, pug, pyrenees, redbone, retriever, ridgeback, rottweiler, saluki, samoyed, schipperke, schnauzer, setter, sheepdog, shiba, shihtzu, spaniel, springer, stbernard, terrier, vizsla, weimaraner, whippet, wolfhound]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Hope it helps.

like image 156
Szymon Stepniak Avatar answered Sep 19 '22 22:09

Szymon Stepniak