$customHeader
Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 15 Next »

Abstract

This code snippet is a subset of Code snippet to make an HTTP call and request data. This code snippet accesses a REST API, requests for JSON data and returns parsed JSON data the response.

Logic

  • Import the HTTPBuilder and the request methods.
  • Access the REST API by creating a new HTTP instance.
  • Request the JSON data passing the method, the content type, and the request configuration closure to the request method.
  • Return the parsed JSON data from the response.

Snippet 

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.JSON
 
// initialize a new builder and give a default URL
def http = new HTTPBuilder("<URL>")
 
http.request(GET,JSON) { req ->
 
  response.success = { resp, jsonData ->
    assert resp.status == 200
	
	return jsonData
  }
 
  // called only for a 404 (not found) status code:
  response."404" = { resp ->
    log.error ("Not found")
  }
}
Placeholders
PlaceholderDescriptionExample
<URL>URLhttp://free.currencyconverterapi.com/api/v5/convert?q=EUR_USD&compact=y
<methodName>Name of the request methodGET
<contentType>Type of the content requested forJSON

Context

The outcome of the code snippet depends on the content type passed to the request method. You could use this code, for example, to get a specific currency conversion rate.

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.JSON
 
// initialize a new builder and give a default URL
def http = new HTTPBuilder("http://free.currencyconverterapi.com/api/v5/convert?q=EUR_USD&compact=y")
 
http.request(GET,JSON) { req ->
 
  response.success = { resp, jsonData ->
    assert resp.status == 200
    if(jsonData){
      return jsonData
    }
    else{
      log.warn("No data returned")
      return null
    }
  }
 
  // called only for a 404 (not found) status code:
  response."404" = { resp ->
    log.error ("Not found")
  }
}

Use cases

On creation of the issue, convert the entered "Bidding amount" from Euros to Dollars.


Reference

Filter by label

There are no items with the selected labels at this time.

  • No labels