Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

...

...

...

...

...

...

...

...

...

...

...

...

...

...

...

...

...

...

...

Abstract

This code snippet fetches a currency conversion rate.

Logic

Initialize a new HTTPBuilder, use the common request types and get is a specialization of the Code snippet to make an HTTP call and request data. It accesses a REST API, and thus requests JSON data and returns the parsed data through a Groovy script written in the Groovy editor of the add-on.

Logic

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

Snippet 

Code Block
languagegroovy
linenumberstrue
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>")
 
def data = http.request(GET,JSON) { req ->
 
  response.success = { resp, readerjsonData ->
    assert resp.status == 200
	return jsonData
  reader.<id>.val
  }
 
  // called only for a 404 (not found) status code:
  response.'"404'" = { resp ->
    println 'log.error ("Not found'")
    return null
  }
}

if (data) {
  // do something with the returned data
}
Placeholders
PlaceholderDescriptionExample
<URL>URLhttp://free.currencyconverterapi.com/api/v5/convert?q=EUR_USD&compact=y
<id>The conversion IdEUR_USD

...

<methodName>Name of the request methodGET
<contentType>Type of the content requested forJSON

Example

The outcome of the code snippet is BigDecimalJSON data. You You could use this code, for example, to convert currency from one to another.get a specific currency conversion rate.

Code Block
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")
 
return http.request(GET,JSON) { req ->
 
  response.success = { resp, jsonData ->
    assert resp.status == 200
    if(jsonData){
      return jsonData.get("EUR_USD").val
    }
    else{
      log.warn("No data returned")
      return null
    }
  }
 
  // called only for a 404 (not found) status code:
  response."404" = { resp ->
    log.error ("Not found")
	return null

  }
}

Reference

Filter by label (Content by label)
showLabelsfalse
max5
spacesKB
showSpacefalse
sortmodified
reversetrue
typepage
cqllabel = "jmwe-server" and type = "page" and space = "KBJMWE"
labelsjmwe-nunjucks jmwe-cloud

...