Abstract
This code snippet is a subset of specialization of the Code snippet to make a an HTTP call and request data. This code snippet requests for JSON in particular It accesses a REST API, and thus requests JSON data and returns the parsed JSON data from the responsedata through a Groovy script written in the Groovy editor of the add-on.
Logic
- Import the HTTPBuilder, GET request methods and the request methodsJSON 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 | ||||
---|---|---|---|---|
| ||||
import groovyx.net.http.HTTPBuilder import static groovyx.net.http.Method.<methodName>GET import static groovyx.net.http.ContentType.<contentType>JSON // initialize a new builder and give a default URL def http = new HTTPBuilder("<URL>") def data = http.request(<methodName>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") return null } } if (data) { // do something with the returned data } |
Placeholders
Placeholder | Description | Example |
---|---|---|
<URL > | URL | http://free.currencyconverterapi.com/api/v5/convert?q=EUR_USD&compact=y |
<methodName> | Name of the request method | GET |
<contentType> | Type of the content requested for | JSON |
...
Example
The outcome of the code snippet depends on the content type passed to the request methodis JSON data. You could use this code, for example, to get a specific currency conversion rate.
Use cases
...
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) | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
...