Search code examples
groovyjenkins-pipelinehttprequestjenkins-shared-libraries

groovy.lang.MissingMethodException: No signature of method: httpRequest() is applicable for argument types: (java.util.LinkedHashMap)


I have the following piece of code that used to work great in a pipeline. I have to move it into a shared library in Jenkins, so created a class for it and made the necessary adjustments.

    def toJson (input) {
       return groovy.json.JsonOutput.toJson(input)
    }

    def void callAPI (args) {
        def apiRequestBody = [
            "prop1": args.param1,
            "prop2": args.param2
        ]
 // Build the request - notice that authentication should happen seamlessly by using Jenkins Credentials
        response = httpRequest (authentication: "${CREDENTIALS_STORED_IN_JENKINS}",
            consoleLogResponseBody: true,
            httpMode: 'POST',
            requestBody: toJson(apiRequestBody),
            url: "${API_URL}",
            customHeaders: [
                [
                    name: 'Content-Type',
                    value: 'application/json; charset=utf-8'
                ],
                [
                    name: 'Accept-Charset',
                    value: 'utf-8'
                ]
            ]
        )

When I call the callAPI (args) method, I get the following error:

Exception groovy.lang.MissingMethodException: No signature of method: MY_PACKAGE_PATH.MY_CLASS.httpRequest() is applicable for argument types: (java.util.LinkedHashMap) values: [[authentication:MYAPI_UID_PW, consoleLogResponseBody:true, ...]]

What am I missing?

Thanks


Solution

  • httpRequest is a DSL command that's not directly available within the context of a class, much like ou can't use sh, bat, or node. See https://www.jenkins.io/doc/book/pipeline/shared-libraries/#accessing-steps for more info about this.

    You can lift code from within a Jenkinsfile and place it in a "var" (or Global Variable) instead, though. If you insist on placing the code in a shared library class, refer to the link above, which would transform your code into (notice the "script" parameter and the script.httpRequest syntax):

     def void callAPI (script, args) {
        def apiRequestBody = [
            "prop1": args.param1,
            "prop2": args.param2
        ]
        // Build the request
        response = script.httpRequest (authentication: "${CREDENTIALS_STORED_IN_JENKINS}",
        // ...
     }